Skip to content

Commit 8c6ae29

Browse files
authored
Update Solution.swift
1 parent 601c7bd commit 8c6ae29

File tree

1 file changed

+19
-26
lines changed

1 file changed

+19
-26
lines changed

lcci/17.15.Longest Word/Solution.swift

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,37 +28,30 @@ class Trie {
2828
}
2929

3030
class Solution {
31-
private let trie = Trie()
32-
3331
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+
}
3744
}
38-
return a > b
45+
return false
3946
}
40-
47+
4148
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
4552
}
46-
trie.insert(word)
53+
trie.insert(w)
4754
}
4855
return ans
4956
}
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+
}

0 commit comments

Comments
 (0)