Skip to content

Commit df08c12

Browse files
authored
feat: add swift implementation to lcof2 problem: No.015 (doocs#3003)
1 parent 220c483 commit df08c12

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

lcof2/剑指 Offer II 015. 字符串中的所有变位词/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,51 @@ function findAnagrams(s: string, p: string): number[] {
213213
}
214214
```
215215

216+
#### Swift
217+
218+
```swift
219+
class Solution {
220+
func findAnagrams(_ s: String, _ p: String) -> [Int] {
221+
let m = s.count
222+
let n = p.count
223+
var ans = [Int]()
224+
225+
if m < n {
226+
return ans
227+
}
228+
229+
var cnt1 = Array(repeating: 0, count: 26)
230+
var cnt2 = Array(repeating: 0, count: 26)
231+
232+
let aAsciiValue = Character("a").asciiValue!
233+
234+
for i in 0..<n {
235+
let sIdx = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i)] - aAsciiValue)
236+
let pIdx = Int(p.utf8[p.utf8.index(p.utf8.startIndex, offsetBy: i)] - aAsciiValue)
237+
cnt1[sIdx] += 1
238+
cnt2[pIdx] += 1
239+
}
240+
241+
if cnt1 == cnt2 {
242+
ans.append(0)
243+
}
244+
245+
for i in n..<m {
246+
let sIdxNew = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i)] - aAsciiValue)
247+
let sIdxOld = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i - n)] - aAsciiValue)
248+
cnt1[sIdxNew] += 1
249+
cnt1[sIdxOld] -= 1
250+
251+
if cnt1 == cnt2 {
252+
ans.append(i - n + 1)
253+
}
254+
}
255+
256+
return ans
257+
}
258+
}
259+
```
260+
216261
<!-- tabs:end -->
217262

218263
<!-- solution:end -->
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
func findAnagrams(_ s: String, _ p: String) -> [Int] {
3+
let m = s.count
4+
let n = p.count
5+
var ans = [Int]()
6+
7+
if m < n {
8+
return ans
9+
}
10+
11+
var cnt1 = Array(repeating: 0, count: 26)
12+
var cnt2 = Array(repeating: 0, count: 26)
13+
14+
let aAsciiValue = Character("a").asciiValue!
15+
16+
for i in 0..<n {
17+
let sIdx = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i)] - aAsciiValue)
18+
let pIdx = Int(p.utf8[p.utf8.index(p.utf8.startIndex, offsetBy: i)] - aAsciiValue)
19+
cnt1[sIdx] += 1
20+
cnt2[pIdx] += 1
21+
}
22+
23+
if cnt1 == cnt2 {
24+
ans.append(0)
25+
}
26+
27+
for i in n..<m {
28+
let sIdxNew = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i)] - aAsciiValue)
29+
let sIdxOld = Int(s.utf8[s.utf8.index(s.utf8.startIndex, offsetBy: i - n)] - aAsciiValue)
30+
cnt1[sIdxNew] += 1
31+
cnt1[sIdxOld] -= 1
32+
33+
if cnt1 == cnt2 {
34+
ans.append(i - n + 1)
35+
}
36+
}
37+
38+
return ans
39+
}
40+
}

0 commit comments

Comments
 (0)