File tree Expand file tree Collapse file tree 2 files changed +85
-0
lines changed
lcof2/剑指 Offer II 065. 最短的单词编码 Expand file tree Collapse file tree 2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change @@ -218,6 +218,51 @@ func dfs(cur *trie, l int) int {
218
218
}
219
219
```
220
220
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
+
221
266
<!-- tabs: end -->
222
267
223
268
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments