File tree Expand file tree Collapse file tree 9 files changed +857
-297
lines changed
solution/0700-0799/0720.Longest Word in Dictionary Expand file tree Collapse file tree 9 files changed +857
-297
lines changed Load Diff Large diffs are not rendered by default.
Load Diff Large diffs are not rendered by default.
Original file line number Diff line number Diff line change 1
- class Solution {
1
+ class Trie {
2
2
public:
3
- string longestWord (vector<string>& words) {
4
- unordered_set<string> s (words.begin (), words.end ());
5
- int cnt = 0 ;
6
- string ans = " " ;
7
- for (auto w : s) {
8
- int n = w.size ();
9
- if (check (w, s)) {
10
- if (cnt < n) {
11
- cnt = n;
12
- ans = w;
13
- } else if (cnt == n && w < ans)
14
- ans = w;
3
+ Trie* children[26 ] = {nullptr };
4
+ bool isEnd = false ;
5
+
6
+ void insert (const string& w) {
7
+ Trie* node = this ;
8
+ for (char c : w) {
9
+ int idx = c - ' a' ;
10
+ if (node->children [idx] == nullptr ) {
11
+ node->children [idx] = new Trie ();
15
12
}
13
+ node = node->children [idx];
16
14
}
17
- return ans ;
15
+ node-> isEnd = true ;
18
16
}
19
17
20
- bool check (string& word, unordered_set<string>& s) {
21
- for (int i = 1 , n = word.size (); i < n; ++i)
22
- if (!s.count (word.substr (0 , i)))
18
+ bool search (const string& w) {
19
+ Trie* node = this ;
20
+ for (char c : w) {
21
+ int idx = c - ' a' ;
22
+ if (node->children [idx] == nullptr || !node->children [idx]->isEnd ) {
23
23
return false ;
24
+ }
25
+ node = node->children [idx];
26
+ }
24
27
return true ;
25
28
}
26
- };
29
+ };
30
+
31
+ class Solution {
32
+ public:
33
+ string longestWord (vector<string>& words) {
34
+ Trie trie;
35
+ for (const string& w : words) {
36
+ trie.insert (w);
37
+ }
38
+
39
+ string ans = " " ;
40
+ for (const string& w : words) {
41
+ if (trie.search (w) && (ans.length () < w.length () || (ans.length () == w.length () && w < ans))) {
42
+ ans = w;
43
+ }
44
+ }
45
+ return ans;
46
+ }
47
+ };
Original file line number Diff line number Diff line change
1
+ type Trie struct {
2
+ children [26 ]* Trie
3
+ isEnd bool
4
+ }
5
+
6
+ func (t * Trie ) insert (w string ) {
7
+ node := t
8
+ for i := 0 ; i < len (w ); i ++ {
9
+ idx := w [i ] - 'a'
10
+ if node .children [idx ] == nil {
11
+ node .children [idx ] = & Trie {}
12
+ }
13
+ node = node .children [idx ]
14
+ }
15
+ node .isEnd = true
16
+ }
17
+
18
+ func (t * Trie ) search (w string ) bool {
19
+ node := t
20
+ for i := 0 ; i < len (w ); i ++ {
21
+ idx := w [i ] - 'a'
22
+ if node .children [idx ] == nil || ! node .children [idx ].isEnd {
23
+ return false
24
+ }
25
+ node = node .children [idx ]
26
+ }
27
+ return true
28
+ }
29
+
1
30
func longestWord (words []string ) string {
2
- s := make ( map [ string ] bool )
31
+ trie := & Trie {}
3
32
for _ , w := range words {
4
- s [ w ] = true
33
+ trie . insert ( w )
5
34
}
6
- cnt := 0
35
+
7
36
ans := ""
8
- check := func (word string ) bool {
9
- for i , n := 1 , len (word ); i < n ; i ++ {
10
- if ! s [word [:i ]] {
11
- return false
12
- }
13
- }
14
- return true
15
- }
16
- for w , _ := range s {
17
- n := len (w )
18
- if check (w ) {
19
- if cnt < n {
20
- cnt , ans = n , w
21
- } else if cnt == n && w < ans {
22
- ans = w
23
- }
37
+ for _ , w := range words {
38
+ if trie .search (w ) && (len (ans ) < len (w ) || (len (ans ) == len (w ) && w < ans )) {
39
+ ans = w
24
40
}
25
41
}
26
42
return ans
27
- }
43
+ }
Original file line number Diff line number Diff line change 1
- class Solution {
2
- private Set <String > s ;
1
+ class Trie {
2
+ private Trie [] children = new Trie [26 ];
3
+ private boolean isEnd = false ;
3
4
4
- public String longestWord (String [] words ) {
5
- s = new HashSet <>(Arrays .asList (words ));
6
- int cnt = 0 ;
7
- String ans = "" ;
8
- for (String w : s ) {
9
- int n = w .length ();
10
- if (check (w )) {
11
- if (cnt < n ) {
12
- cnt = n ;
13
- ans = w ;
14
- } else if (cnt == n && w .compareTo (ans ) < 0 ) {
15
- ans = w ;
16
- }
5
+ public void insert (String w ) {
6
+ Trie node = this ;
7
+ for (char c : w .toCharArray ()) {
8
+ int idx = c - 'a' ;
9
+ if (node .children [idx ] == null ) {
10
+ node .children [idx ] = new Trie ();
17
11
}
12
+ node = node .children [idx ];
18
13
}
19
- return ans ;
14
+ node . isEnd = true ;
20
15
}
21
16
22
- private boolean check (String word ) {
23
- for (int i = 1 , n = word .length (); i < n ; ++i ) {
24
- if (!s .contains (word .substring (0 , i ))) {
17
+ public boolean search (String w ) {
18
+ Trie node = this ;
19
+ for (char c : w .toCharArray ()) {
20
+ int idx = c - 'a' ;
21
+ if (node .children [idx ] == null || !node .children [idx ].isEnd ) {
25
22
return false ;
26
23
}
24
+ node = node .children [idx ];
27
25
}
28
26
return true ;
29
27
}
30
- }
28
+ }
29
+
30
+ class Solution {
31
+ public String longestWord (String [] words ) {
32
+ Trie trie = new Trie ();
33
+ for (String w : words ) {
34
+ trie .insert (w );
35
+ }
36
+ String ans = "" ;
37
+ for (String w : words ) {
38
+ if (trie .search (w )
39
+ && (ans .length () < w .length ()
40
+ || (ans .length () == w .length () && w .compareTo (ans ) < 0 ))) {
41
+ ans = w ;
42
+ }
43
+ }
44
+ return ans ;
45
+ }
46
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string[] } words
3
+ * @return {string }
4
+ */
5
+ var longestWord = function ( words ) {
6
+ const trie = new Trie ( ) ;
7
+ for ( const w of words ) {
8
+ trie . insert ( w ) ;
9
+ }
10
+
11
+ let ans = '' ;
12
+ for ( const w of words ) {
13
+ if ( trie . search ( w ) && ( ans . length < w . length || ( ans . length === w . length && w < ans ) ) ) {
14
+ ans = w ;
15
+ }
16
+ }
17
+ return ans ;
18
+ } ;
19
+
20
+ class Trie {
21
+ constructor ( ) {
22
+ this . children = Array ( 26 ) . fill ( null ) ;
23
+ this . isEnd = false ;
24
+ }
25
+
26
+ insert ( w ) {
27
+ let node = this ;
28
+ for ( let i = 0 ; i < w . length ; i ++ ) {
29
+ const idx = w . charCodeAt ( i ) - 'a' . charCodeAt ( 0 ) ;
30
+ if ( node . children [ idx ] === null ) {
31
+ node . children [ idx ] = new Trie ( ) ;
32
+ }
33
+ node = node . children [ idx ] ;
34
+ }
35
+ node . isEnd = true ;
36
+ }
37
+
38
+ search ( w ) {
39
+ let node = this ;
40
+ for ( let i = 0 ; i < w . length ; i ++ ) {
41
+ const idx = w . charCodeAt ( i ) - 'a' . charCodeAt ( 0 ) ;
42
+ if ( node . children [ idx ] === null || ! node . children [ idx ] . isEnd ) {
43
+ return false ;
44
+ }
45
+ node = node . children [ idx ] ;
46
+ }
47
+ return true ;
48
+ }
49
+ }
Original file line number Diff line number Diff line change
1
+ class Trie :
2
+ def __init__ (self ):
3
+ self .children : List [Optional [Trie ]] = [None ] * 26
4
+ self .is_end = False
5
+
6
+ def insert (self , w : str ):
7
+ node = self
8
+ for c in w :
9
+ idx = ord (c ) - ord ("a" )
10
+ if node .children [idx ] is None :
11
+ node .children [idx ] = Trie ()
12
+ node = node .children [idx ]
13
+ node .is_end = True
14
+
15
+ def search (self , w : str ) -> bool :
16
+ node = self
17
+ for c in w :
18
+ idx = ord (c ) - ord ("a" )
19
+ if node .children [idx ] is None :
20
+ return False
21
+ node = node .children [idx ]
22
+ if not node .is_end :
23
+ return False
24
+ return True
25
+
26
+
1
27
class Solution :
2
28
def longestWord (self , words : List [str ]) -> str :
3
- cnt , ans = 0 , ''
4
- s = set ( words )
5
- for w in s :
6
- n = len ( w )
7
- if all ( w [: i ] in s for i in range ( 1 , n )) :
8
- if cnt < n :
9
- cnt , ans = n , w
10
- elif cnt == n and w < ans :
11
- ans = w
29
+ trie = Trie ()
30
+ for w in words :
31
+ trie . insert ( w )
32
+ ans = ""
33
+ for w in words :
34
+ if trie . search ( w ) and (
35
+ len ( ans ) < len ( w ) or ( len ( ans ) == len ( w ) and ans > w )
36
+ ) :
37
+ ans = w
12
38
return ans
Original file line number Diff line number Diff line change 1
- impl Solution {
2
- pub fn longest_word ( mut words : Vec < String > ) -> String {
3
- words. sort_unstable_by ( |a, b| ( b. len ( ) , a) . cmp ( & ( a. len ( ) , b) ) ) ;
4
- for word in words. iter ( ) {
5
- let mut is_pass = true ;
6
- for i in 1 ..=word. len ( ) {
7
- if !words. contains ( & word[ ..i] . to_string ( ) ) {
8
- is_pass = false ;
9
- break ;
10
- }
1
+ struct Trie {
2
+ children : [ Option < Box < Trie > > ; 26 ] ,
3
+ is_end : bool ,
4
+ }
5
+
6
+ impl Trie {
7
+ fn new ( ) -> Self {
8
+ Trie {
9
+ children : Default :: default ( ) ,
10
+ is_end : false ,
11
+ }
12
+ }
13
+
14
+ fn insert ( & mut self , w : & str ) {
15
+ let mut node = self ;
16
+ for c in w. chars ( ) {
17
+ let idx = ( c as usize ) - ( 'a' as usize ) ;
18
+ if node. children [ idx] . is_none ( ) {
19
+ node. children [ idx] = Some ( Box :: new ( Trie :: new ( ) ) ) ;
20
+ }
21
+ node = node. children [ idx] . as_mut ( ) . unwrap ( ) ;
22
+ }
23
+ node. is_end = true ;
24
+ }
25
+
26
+ fn search ( & self , w : & str ) -> bool {
27
+ let mut node = self ;
28
+ for c in w. chars ( ) {
29
+ let idx = ( c as usize ) - ( 'a' as usize ) ;
30
+ if node. children [ idx] . is_none ( ) || !node. children [ idx] . as_ref ( ) . unwrap ( ) . is_end {
31
+ return false ;
11
32
}
12
- if is_pass {
13
- return word. clone ( ) ;
33
+ node = node. children [ idx] . as_ref ( ) . unwrap ( ) ;
34
+ }
35
+ true
36
+ }
37
+ }
38
+
39
+ impl Solution {
40
+ pub fn longest_word ( words : Vec < String > ) -> String {
41
+ let mut trie = Trie :: new ( ) ;
42
+ for w in & words {
43
+ trie. insert ( w) ;
44
+ }
45
+
46
+ let mut ans = String :: new ( ) ;
47
+ for w in words {
48
+ if trie. search ( & w) && ( ans. len ( ) < w. len ( ) || ( ans. len ( ) == w. len ( ) && w < ans) ) {
49
+ ans = w;
14
50
}
15
51
}
16
- String :: new ( )
52
+ ans
17
53
}
18
54
}
You can’t perform that action at this time.
0 commit comments