Skip to content

Commit 414721e

Browse files
committed
feat: add swift implementation to lcof2 problem: No.065
1 parent 0de04e4 commit 414721e

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

lcof2/剑指 Offer II 065. 最短的单词编码/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,51 @@ func dfs(cur *trie, l int) int {
218218
}
219219
```
220220

221+
#### Swift
222+
223+
```swift
224+
class Trie {
225+
var children = [Trie?](repeating: nil, count: 26)
226+
}
227+
228+
class Solution {
229+
func minimumLengthEncoding(_ words: [String]) -> Int {
230+
let root = Trie()
231+
232+
for word in words {
233+
var current = root
234+
for char in word.reversed() {
235+
let index = Int(char.asciiValue! - Character("a").asciiValue!)
236+
if current.children[index] == nil {
237+
current.children[index] = Trie()
238+
}
239+
current = current.children[index]!
240+
}
241+
}
242+
243+
return dfs(root, 1)
244+
}
245+
246+
private func dfs(_ current: Trie, _ length: Int) -> Int {
247+
var isLeaf = true
248+
var result = 0
249+
250+
for child in current.children {
251+
if let child = child {
252+
isLeaf = false
253+
result += dfs(child, length + 1)
254+
}
255+
}
256+
257+
if isLeaf {
258+
result += length
259+
}
260+
261+
return result
262+
}
263+
}
264+
```
265+
221266
<!-- tabs:end -->
222267

223268
<!-- solution:end -->
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Trie {
2+
var children = [Trie?](repeating: nil, count: 26)
3+
}
4+
5+
class Solution {
6+
func minimumLengthEncoding(_ words: [String]) -> Int {
7+
let root = Trie()
8+
9+
for word in words {
10+
var current = root
11+
for char in word.reversed() {
12+
let index = Int(char.asciiValue! - Character("a").asciiValue!)
13+
if current.children[index] == nil {
14+
current.children[index] = Trie()
15+
}
16+
current = current.children[index]!
17+
}
18+
}
19+
20+
return dfs(root, 1)
21+
}
22+
23+
private func dfs(_ current: Trie, _ length: Int) -> Int {
24+
var isLeaf = true
25+
var result = 0
26+
27+
for child in current.children {
28+
if let child = child {
29+
isLeaf = false
30+
result += dfs(child, length + 1)
31+
}
32+
}
33+
34+
if isLeaf {
35+
result += length
36+
}
37+
38+
return result
39+
}
40+
}

0 commit comments

Comments
 (0)