Skip to content

Commit 05c535b

Browse files
authored
feat: add swift implementation to lcof2 problem: No.014 (doocs#2984)
1 parent d5ca3cc commit 05c535b

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,44 @@ function checkInclusion(s1: string, s2: string): boolean {
440440
}
441441
```
442442

443+
#### Swift
444+
445+
```swift
446+
class Solution {
447+
func checkInclusion(_ s1: String, _ s2: String) -> Bool {
448+
let m = s1.count
449+
let n = s2.count
450+
if m > n {
451+
return false
452+
}
453+
454+
var cnt1 = [Int](repeating: 0, count: 26)
455+
var cnt2 = [Int](repeating: 0, count: 26)
456+
let aAscii = Character("a").asciiValue!
457+
458+
for i in 0..<m {
459+
cnt1[Int(s1[s1.index(s1.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
460+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
461+
}
462+
463+
if cnt1 == cnt2 {
464+
return true
465+
}
466+
467+
for i in m..<n {
468+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
469+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i - m)].asciiValue! - aAscii)] -= 1
470+
471+
if cnt1 == cnt2 {
472+
return true
473+
}
474+
}
475+
476+
return false
477+
}
478+
}
479+
```
480+
443481
<!-- tabs:end -->
444482

445483
<!-- solution:end -->
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
func checkInclusion(_ s1: String, _ s2: String) -> Bool {
3+
let m = s1.count
4+
let n = s2.count
5+
if m > n {
6+
return false
7+
}
8+
9+
var cnt1 = [Int](repeating: 0, count: 26)
10+
var cnt2 = [Int](repeating: 0, count: 26)
11+
let aAscii = Character("a").asciiValue!
12+
13+
for i in 0..<m {
14+
cnt1[Int(s1[s1.index(s1.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
15+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
16+
}
17+
18+
if cnt1 == cnt2 {
19+
return true
20+
}
21+
22+
for i in m..<n {
23+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i)].asciiValue! - aAscii)] += 1
24+
cnt2[Int(s2[s2.index(s2.startIndex, offsetBy: i - m)].asciiValue! - aAscii)] -= 1
25+
26+
if cnt1 == cnt2 {
27+
return true
28+
}
29+
}
30+
31+
return false
32+
}
33+
}

0 commit comments

Comments
 (0)