File tree 2 files changed +50
-0
lines changed
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ use std:: collections:: HashMap ;
2
+ use std:: collections:: HashSet ;
3
+
4
+ struct Solution ;
5
+
6
+ impl Solution {
7
+ pub fn most_common_word ( paragraph : String , banned : Vec < String > ) -> String {
8
+ let paragraph = paragraph
9
+ . replace ( "," , " " )
10
+ . replace ( "." , " " )
11
+ . replace ( "!" , " " )
12
+ . replace ( "?" , " " )
13
+ . replace ( "'" , " " )
14
+ . replace ( ";" , " " ) ;
15
+ let words: Vec < & str > = paragraph. split_ascii_whitespace ( ) . collect ( ) ;
16
+ let mut h_map_words: HashMap < String , u32 > = HashMap :: new ( ) ;
17
+ let h_map_banned: HashSet < String > = banned. into_iter ( ) . collect ( ) ;
18
+
19
+ for word in words {
20
+ let w = word. to_string ( ) . to_lowercase ( ) ;
21
+ if !h_map_banned. contains ( & w) {
22
+ let count = h_map_words. entry ( w) . or_insert ( 0 ) ;
23
+ * count += 1 ;
24
+ }
25
+ }
26
+
27
+ let mut max_word: String = "" . to_string ( ) ;
28
+ let mut max_count: u32 = 0 ;
29
+ for ( v, i) in h_map_words {
30
+ if max_count < i {
31
+ max_count = i;
32
+ max_word = v. to_string ( ) ;
33
+ }
34
+ }
35
+ max_word
36
+ }
37
+ }
38
+
39
+ #[ test]
40
+ fn test ( ) {
41
+ assert_eq ! (
42
+ Solution :: most_common_word(
43
+ "Bob hit a ball, the hit BALL flew far after it was hit." . to_string( ) ,
44
+ vec_string![ "hit" ]
45
+ ) ,
46
+ "ball" . to_string( )
47
+ ) ;
48
+ }
Original file line number Diff line number Diff line change @@ -126,6 +126,8 @@ mod _0771_jewels_and_stones;
126
126
//
127
127
mod _0796_rotate_string;
128
128
//
129
+ mod _0819_most_common_word;
130
+ //
129
131
mod _0844_backspace_string_compare;
130
132
//
131
133
mod _0905_sort_array_by_parity;
You can’t perform that action at this time.
0 commit comments