File tree 2 files changed +51
-0
lines changed
lcof2/剑指 Offer II 066. 单词之和
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -196,6 +196,34 @@ func (this *MapSum) Sum(prefix string) int {
196
196
*/
197
197
```
198
198
199
+ #### Swift
200
+
201
+ ``` swift
202
+ class MapSum {
203
+ private var data: [String : Int ]
204
+ private var t: [String : Int ]
205
+
206
+ init () {
207
+ data = [String : Int ]()
208
+ t = [String : Int ]()
209
+ }
210
+
211
+ func insert (_ key : String , _ val : Int ) {
212
+ let old = t[key] ?? 0
213
+ t[key] = val
214
+ for i in 1 ... key.count {
215
+ let endIndex = key.index (key.startIndex , offsetBy : i)
216
+ let k = String (key[key.startIndex ..< endIndex])
217
+ data[k, default : 0 ] += (val - old)
218
+ }
219
+ }
220
+
221
+ func sum (_ prefix : String ) -> Int {
222
+ return data[prefix ] ?? 0
223
+ }
224
+ }
225
+ ```
226
+
199
227
<!-- tabs:end -->
200
228
201
229
<!-- solution:end -->
Original file line number Diff line number Diff line change
1
+ class MapSum {
2
+ private var data : [ String : Int ]
3
+ private var t : [ String : Int ]
4
+
5
+ init ( ) {
6
+ data = [ String: Int] ( )
7
+ t = [ String: Int] ( )
8
+ }
9
+
10
+ func insert( _ key: String , _ val: Int ) {
11
+ let old = t [ key] ?? 0
12
+ t [ key] = val
13
+ for i in 1 ... key. count {
14
+ let endIndex = key. index ( key. startIndex, offsetBy: i)
15
+ let k = String ( key [ key. startIndex..< endIndex] )
16
+ data [ k, default: 0 ] += ( val - old)
17
+ }
18
+ }
19
+
20
+ func sum( _ prefix: String ) -> Int {
21
+ return data [ prefix] ?? 0
22
+ }
23
+ }
You can’t perform that action at this time.
0 commit comments