File tree 1 file changed +32
-0
lines changed
scripts/algorithms/L/Longest Word in Dictionary
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 6 ms (Top 66.6%) | Memory: 2.18 MB (Top 100.0%)
2
+
3
+ impl Solution {
4
+ pub fn longest_word ( words : Vec < String > ) -> String {
5
+ let mut m = std:: collections:: HashMap :: new ( ) ;
6
+ for w in words {
7
+ m. entry ( w. len ( ) ) . or_insert ( Vec :: new ( ) ) . push ( w) ;
8
+ }
9
+ let mut cur = 2_usize ;
10
+ let mut level = Vec :: new ( ) ;
11
+ if let Some ( v) = m. get ( & 1 ) {
12
+ level = v. clone ( ) ;
13
+ } else {
14
+ return String :: new ( )
15
+ }
16
+ loop {
17
+ let mut new_level = Vec :: new ( ) ;
18
+ if let Some ( v) = m. get ( & cur) {
19
+ for word in v {
20
+ if level. iter ( ) . any ( |w| word. starts_with ( w) ) {
21
+ new_level. push ( word. clone ( ) ) ;
22
+ }
23
+ }
24
+ }
25
+ if new_level. is_empty ( ) {
26
+ return level. iter ( ) . min ( ) . unwrap ( ) . to_string ( )
27
+ }
28
+ level = new_level;
29
+ cur += 1 ;
30
+ }
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments