File tree Expand file tree Collapse file tree 1 file changed +19
-26
lines changed Expand file tree Collapse file tree 1 file changed +19
-26
lines changed Original file line number Diff line number Diff line change @@ -28,37 +28,30 @@ class Trie {
28
28
}
29
29
30
30
class Solution {
31
- private let trie = Trie ( )
32
-
33
31
func longestWord( _ words: [ String ] ) -> String {
34
- let sortedWords = words. sorted { a, b in
35
- if a. count != b. count {
36
- return a. count < b. count
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
37
+ if w. isEmpty {
38
+ return true
39
+ }
40
+ for i in 1 ... w. count {
41
+ if trie. search ( String ( w. prefix ( i) ) ) && dfs ( String ( w. suffix ( w. count - i) ) ) {
42
+ return true
43
+ }
37
44
}
38
- return a > b
45
+ return false
39
46
}
40
-
47
+
41
48
var ans = " "
42
- for word in sortedWords {
43
- if dfs ( word , " " ) {
44
- ans = word
49
+ for w in words {
50
+ if dfs ( w ) {
51
+ ans = w
45
52
}
46
- trie. insert ( word )
53
+ trie. insert ( w )
47
54
}
48
55
return ans
49
56
}
50
-
51
- private func dfs( _ word: String , _ prefix: String ) -> Bool {
52
- if prefix. isEmpty {
53
- return true
54
- }
55
- for i in 1 ... prefix. count {
56
- let index = prefix. index ( prefix. startIndex, offsetBy: i)
57
- let subPrefix = String ( prefix [ ..< index] )
58
- if trie. search ( subPrefix) && dfs ( word, String ( prefix [ index... ] ) ) {
59
- return true
60
- }
61
- }
62
- return false
63
- }
64
- }
57
+ }
You can’t perform that action at this time.
0 commit comments