diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" index 879a1b2817d3f..07b44e6fab882 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" @@ -218,6 +218,51 @@ func dfs(cur *trie, l int) int { } ``` +#### Swift + +```swift +class Trie { + var children = [Trie?](repeating: nil, count: 26) +} + +class Solution { + func minimumLengthEncoding(_ words: [String]) -> Int { + let root = Trie() + + for word in words { + var current = root + for char in word.reversed() { + let index = Int(char.asciiValue! - Character("a").asciiValue!) + if current.children[index] == nil { + current.children[index] = Trie() + } + current = current.children[index]! + } + } + + return dfs(root, 1) + } + + private func dfs(_ current: Trie, _ length: Int) -> Int { + var isLeaf = true + var result = 0 + + for child in current.children { + if let child = child { + isLeaf = false + result += dfs(child, length + 1) + } + } + + if isLeaf { + result += length + } + + return result + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.swift" new file mode 100644 index 0000000000000..1bc6eb4e81d63 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/Solution.swift" @@ -0,0 +1,40 @@ +class Trie { + var children = [Trie?](repeating: nil, count: 26) +} + +class Solution { + func minimumLengthEncoding(_ words: [String]) -> Int { + let root = Trie() + + for word in words { + var current = root + for char in word.reversed() { + let index = Int(char.asciiValue! - Character("a").asciiValue!) + if current.children[index] == nil { + current.children[index] = Trie() + } + current = current.children[index]! + } + } + + return dfs(root, 1) + } + + private func dfs(_ current: Trie, _ length: Int) -> Int { + var isLeaf = true + var result = 0 + + for child in current.children { + if let child = child { + isLeaf = false + result += dfs(child, length + 1) + } + } + + if isLeaf { + result += length + } + + return result + } +} \ No newline at end of file