Skip to content

Commit e4d90d7

Browse files
authoredJul 1, 2024
feat: add swift implementation to lcof2 problem: No.066 (doocs#3180)
1 parent 94cba94 commit e4d90d7

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎lcof2/剑指 Offer II 066. 单词之和/README.md

+28
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,34 @@ func (this *MapSum) Sum(prefix string) int {
196196
*/
197197
```
198198

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+
199227
<!-- tabs:end -->
200228

201229
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}

0 commit comments

Comments
 (0)