判断字符串s2的连续子串是否包含s1的排列。
双指针,保证count值不为正的情况下,判断是否存在一个区间,使得长度恰好为s1
- 时间复杂度O(m + n),空间复杂度O(1)
- Runtime: 84 ms, faster than 95.47%
- Memory Usage: 40.2 MB, less than 92.33%
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var checkInclusion = function(s1, s2) {
const m = s1.length;
const n = s2.length;
if (m > n) {
return false;
}
const count = new Array(26).fill(0);
for (let i = 0; i < m; i++) {
count[s1[i].charCodeAt() - 'a'.charCodeAt()]--;
}
let left = 0;
for (let right = 0; right < n; right++) {
const cur = s2[right].charCodeAt() - 'a'.charCodeAt();
count[cur]++;
while(count[cur] > 0) {
count[s2[left].charCodeAt() - 'a'.charCodeAt()]--;
left++;
}
if (right - left + 1 === m) {
return true;
}
}
return false;
};
网友评论