File tree Expand file tree Collapse file tree 9 files changed +451
-476
lines changed Expand file tree Collapse file tree 9 files changed +451
-476
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 {
2+ public:
3+ string longestWord (vector<string>& words) {
4+ unordered_set<string> s (words.begin (), words.end ());
5+ ranges::sort (words, [&](const string& a, const string& b) {
6+ return a.size () > b.size () || (a.size () == b.size () && a < b);
7+ });
8+ auto dfs = [&](this auto && dfs, string w) -> bool {
9+ if (w.empty ()) {
10+ return true ;
11+ }
12+ for (int k = 1 ; k <= w.size (); ++k) {
13+ if (s.contains (w.substr (0 , k)) && dfs (w.substr (k))) {
14+ return true ;
15+ }
16+ }
17+ return false ;
18+ };
19+ for (const string& w : words) {
20+ s.erase (w);
21+ if (dfs (w)) {
22+ return w;
23+ }
24+ }
25+ return " " ;
26+ }
27+ };
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 newTrie () * Trie {
7- return & Trie {}
8- }
9- func (this * Trie ) insert (word string ) {
10- node := this
11- for _ , c := range word {
12- c -= 'a'
13- if node .children [c ] == nil {
14- node .children [c ] = newTrie ()
15- }
16- node = node .children [c ]
17- }
18- node .isEnd = true
19- }
20-
21- func (this * Trie ) search (word string ) bool {
22- node := this
23- for _ , c := range word {
24- c -= 'a'
25- if node .children [c ] == nil {
26- return false
27- }
28- node = node .children [c ]
29- }
30- return node .isEnd
31- }
32-
331func longestWord (words []string ) string {
2+ s := map [string ]bool {}
3+ for _ , w := range words {
4+ s [w ] = true
5+ }
346 sort .Slice (words , func (i , j int ) bool {
35- a , b := words [i ], words [j ]
36- if len (a ) != len (b ) {
37- return len (a ) < len (b )
38- }
39- return a > b
7+ return len (words [i ]) > len (words [j ]) || (len (words [i ]) == len (words [j ]) && words [i ] < words [j ])
408 })
41- trie := newTrie ()
429 var dfs func (string ) bool
4310 dfs = func (w string ) bool {
4411 if len (w ) == 0 {
4512 return true
4613 }
47- for i := 1 ; i <= len (w ); i ++ {
48- if trie . search ( w [:i ]) && dfs (w [i :]) {
14+ for k := 1 ; k <= len (w ); k ++ {
15+ if s [ w [:k ]] && dfs (w [k :]) {
4916 return true
5017 }
5118 }
5219 return false
5320 }
54- ans := ""
5521 for _ , w := range words {
22+ s [w ] = false
5623 if dfs (w ) {
57- ans = w
24+ return w
5825 }
59- trie .insert (w )
6026 }
61- return ans
62- }
27+ return ""
28+ }
Original file line number Diff line number Diff line change 1- class Trie {
2- Trie [] children = new Trie [26 ];
3- boolean isEnd ;
4-
5- void insert (String word ) {
6- Trie node = this ;
7- for (char c : word .toCharArray ()) {
8- c -= 'a' ;
9- if (node .children [c ] == null ) {
10- node .children [c ] = new Trie ();
11- }
12- node = node .children [c ];
13- }
14- node .isEnd = true ;
15- }
16-
17- boolean search (String word ) {
18- Trie node = this ;
19- for (char c : word .toCharArray ()) {
20- c -= 'a' ;
21- if (node .children [c ] == null ) {
22- return false ;
23- }
24- node = node .children [c ];
25- }
26- return node .isEnd ;
27- }
28- }
29-
301class Solution {
31- private Trie trie = new Trie ();
2+ private Set < String > s = new HashSet <> ();
323
334 public String longestWord (String [] words ) {
5+ for (String w : words ) {
6+ s .add (w );
7+ }
348 Arrays .sort (words , (a , b ) -> {
359 if (a .length () != b .length ()) {
36- return a .length () - b .length ();
10+ return b .length () - a .length ();
3711 }
38- return b .compareTo (a );
12+ return a .compareTo (b );
3913 });
40- String ans = "" ;
4114 for (String w : words ) {
15+ s .remove (w );
4216 if (dfs (w )) {
43- ans = w ;
17+ return w ;
4418 }
45- trie .insert (w );
4619 }
47- return ans ;
20+ return "" ;
4821 }
4922
5023 private boolean dfs (String w ) {
51- if ("" . equals ( w ) ) {
24+ if (w . length () == 0 ) {
5225 return true ;
5326 }
54- for (int i = 1 ; i <= w .length (); ++i ) {
55- if (trie . search (w .substring (0 , i )) && dfs (w .substring (i ))) {
27+ for (int k = 1 ; k <= w .length (); ++k ) {
28+ if (s . contains (w .substring (0 , k )) && dfs (w .substring (k ))) {
5629 return true ;
5730 }
5831 }
5932 return false ;
6033 }
61- }
34+ }
Original file line number Diff line number Diff line change 1- class Trie :
2- def __init__ (self ):
3- self .children = [None ] * 26
4- self .is_end = False
5-
6- def insert (self , word ):
7- node = self
8- for c in word :
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 , word ):
16- node = self
17- for c in word :
18- idx = ord (c ) - ord ('a' )
19- if node .children [idx ] is None :
20- return False
21- node = node .children [idx ]
22- return node .is_end
23-
24-
251class Solution :
262 def longestWord (self , words : List [str ]) -> str :
27- def cmp (a , b ):
28- if len (a ) != len (b ):
29- return len (a ) - len (b )
30- return - 1 if a > b else 1
31-
32- def dfs (w ):
33- return not w or any (
34- trie .search (w [:i ]) and dfs (w [i :]) for i in range (1 , len (w ) + 1 )
35- )
3+ def dfs (w : str ) -> bool :
4+ if not w :
5+ return True
6+ for k in range (1 , len (w ) + 1 ):
7+ if w [:k ] in s and dfs (w [k :]):
8+ return True
9+ return False
3610
37- words .sort (key = cmp_to_key (cmp ))
38- trie = Trie ()
39- ans = ""
11+ s = set (words )
12+ words .sort (key = lambda x : (- len (x ), x ))
4013 for w in words :
14+ s .remove (w )
4115 if dfs (w ):
42- ans = w
43- trie .insert (w )
44- return ans
16+ return w
17+ return ""
Original file line number Diff line number Diff line change 1+ use std:: collections:: HashSet ;
2+
3+ impl Solution {
4+ pub fn longest_word ( words : Vec < String > ) -> String {
5+ let mut s: HashSet < String > = words. iter ( ) . cloned ( ) . collect ( ) ;
6+ let mut words = words;
7+ words. sort_by ( |a, b| b. len ( ) . cmp ( & a. len ( ) ) . then ( a. cmp ( b) ) ) ;
8+
9+ fn dfs ( w : String , s : & mut HashSet < String > ) -> bool {
10+ if w. is_empty ( ) {
11+ return true ;
12+ }
13+ for k in 1 ..=w. len ( ) {
14+ if s. contains ( & w[ 0 ..k] ) && dfs ( w[ k..] . to_string ( ) , s) {
15+ return true ;
16+ }
17+ }
18+ false
19+ }
20+ for w in words {
21+ s. remove ( & w) ;
22+ if dfs ( w. clone ( ) , & mut s) {
23+ return w;
24+ }
25+ }
26+ String :: new ( )
27+ }
28+ }
Original file line number Diff line number Diff line change 1- class Trie {
2- var children = [ Trie? ] ( repeating: nil , count: 26 )
3- var isEnd = false
4-
5- func insert( _ word: String ) {
6- var node = self
7- for ch in word {
8- let index = Int ( ch. asciiValue! - Character( " a " ) . asciiValue!)
9- if node. children [ index] == nil {
10- node. children [ index] = Trie ( )
1+ class Solution {
2+ func longestWord( _ words: [ String ] ) -> String {
3+ var s : Set < String > = Set ( words)
4+ var words = words
5+ words. sort { ( a, b) -> Bool in
6+ if a. count == b. count {
7+ return a < b
8+ } else {
9+ return a. count > b. count
1110 }
12- node = node. children [ index] !
1311 }
14- node. isEnd = true
15- }
1612
17- func search( _ word: String ) -> Bool {
18- var node = self
19- for ch in word {
20- let index = Int ( ch. asciiValue! - Character( " a " ) . asciiValue!)
21- if node. children [ index] == nil {
22- return false
23- }
24- node = node. children [ index] !
25- }
26- return node. isEnd
27- }
28- }
29-
30- class Solution {
31- func longestWord( _ words: [ String ] ) -> String {
32- var words = words. sorted ( by: { $0. count < $1. count || ( $0. count == $1. count && $0 > $1) } )
33- let trie = Trie ( )
34-
35- var dfs : ( ( String ) -> Bool ) !
36- dfs = { w in
13+ func dfs( _ w: String ) -> Bool {
3714 if w. isEmpty {
3815 return true
3916 }
40- for i in 1 ... w. count {
41- if trie. search ( String ( w. prefix ( i) ) ) && dfs ( String ( w. suffix ( w. count - i) ) ) {
17+ for k in 1 ... w. count {
18+ let prefix = String ( w. prefix ( k) )
19+ if s. contains ( prefix) && dfs ( String ( w. dropFirst ( k) ) ) {
4220 return true
4321 }
4422 }
4523 return false
4624 }
47-
48- var ans = " "
25+
4926 for w in words {
27+ s. remove ( w)
5028 if dfs ( w) {
51- ans = w
29+ return w
5230 }
53- trie. insert ( w)
5431 }
55- return ans
32+
33+ return " "
5634 }
5735}
Original file line number Diff line number Diff line change 1+ function longestWord ( words : string [ ] ) : string {
2+ const s = new Set ( words ) ;
3+
4+ words . sort ( ( a , b ) => ( a . length === b . length ? a . localeCompare ( b ) : b . length - a . length ) ) ;
5+
6+ const dfs = ( w : string ) : boolean => {
7+ if ( w === '' ) {
8+ return true ;
9+ }
10+ for ( let k = 1 ; k <= w . length ; ++ k ) {
11+ if ( s . has ( w . substring ( 0 , k ) ) && dfs ( w . substring ( k ) ) ) {
12+ return true ;
13+ }
14+ }
15+ return false ;
16+ } ;
17+
18+ for ( const w of words ) {
19+ s . delete ( w ) ;
20+ if ( dfs ( w ) ) {
21+ return w ;
22+ }
23+ }
24+
25+ return '' ;
26+ }
You can’t perform that action at this time.
0 commit comments