567. 字符串的排列

题目链接:https://leetcode-cn.com/problems/permutation-in-string/
执行用时:44 ms, 在所有 Swift 提交中击败了84.00%的用户
内存消耗:14.2 MB, 在所有 Swift 提交中击败了38.00%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
func checkInclusion(_ s1: String, _ s2: String) -> Bool {
if s1.count > s2.count {
return false
}
let a = Array(s1), b = Array(s2), m = s1.count, n = s2.count
var count1 = [Int](repeating: 0, count: 26)
var count2 = [Int](repeating: 0, count: 26)
//比较短字符串长度下是否是对应排列的子串,检查元素
for i in 0 ..< m {
count1[Int(a[i].asciiValue!) - 97] += 1
count2[Int(b[i].asciiValue!) - 97] += 1
}
if count1.elementsEqual(count2) {
return true
}
for i in m ..< n {
//滑动窗口向后移动,去掉滑动窗口前一个元素
count2[Int(b[i].asciiValue!) - 97] += 1
count2[Int(b[i-m].asciiValue!) - 97] -= 1
if count1.elementsEqual(count2) {
return true
}
}
return false
}
}

567. 字符串的排列
https://pisces34.github.io/2021/08/26/leetcode/567/
发布于
2021年8月26日
许可协议