@@ -108,6 +108,62 @@ func respace(dictionary []string, sentence string) int {
108
108
}
109
109
```
110
110
111
+ ``` swift
112
+ class TrieNode {
113
+ var children: [TrieNode? ] = Array (repeating : nil , count : 26 )
114
+ var isEndOfWord = false
115
+ }
116
+
117
+ class Trie {
118
+ private let root = TrieNode ()
119
+
120
+ func insert (_ word : String ) {
121
+ var node = root
122
+ for char in word {
123
+ let index = Int (char.asciiValue ! - Character (" a" ).asciiValue ! )
124
+ if node.children[index] == nil {
125
+ node.children [index] = TrieNode ()
126
+ }
127
+ node = node.children [index]!
128
+ }
129
+ node.isEndOfWord = true
130
+ }
131
+
132
+ func search (_ sentence : Array <Character >, start : Int , end : Int ) -> Bool {
133
+ var node = root
134
+ for i in start... end {
135
+ let index = Int (sentence[i].asciiValue ! - Character (" a" ).asciiValue ! )
136
+ guard let nextNode = node.children[index] else {
137
+ return false
138
+ }
139
+ node = nextNode
140
+ }
141
+ return node.isEndOfWord
142
+ }
143
+ }
144
+
145
+ class Solution {
146
+ func respace (_ dictionary : [String ], _ sentence : String ) -> Int {
147
+ let n = sentence.count
148
+ guard n > 0 else { return 0 }
149
+ let trie = Trie ()
150
+ dictionary.forEach { trie.insert ($0 ) }
151
+ let chars = Array (sentence)
152
+ var dp = Array (repeating : Int .max , count : n + 1 )
153
+ dp[0 ] = 0
154
+ for i in 1 ... n {
155
+ dp[i] = dp[i - 1 ] + 1
156
+ for j in 0 ..< i {
157
+ if trie.search (chars, start : j, end : i - 1 ) {
158
+ dp[i] = min (dp[i], dp[j])
159
+ }
160
+ }
161
+ }
162
+ return dp[n]
163
+ }
164
+ }
165
+ ```
166
+
111
167
<!-- tabs: end -->
112
168
113
169
<!-- end -->
0 commit comments