分类:力扣题解
- 字符串的排列
给你两个字符串 s1 和 s2 ,写一个函数来判断 s2 是否包含 s1 的排列。如果是,返回 true ;否则,返回 false 。
换句话说,s1 的排列之一是 s2 的 子串 。
示例
示例 1:
输入:s1 = “ab” s2 = “eidbaooo”
输出:true
解释:s2 包含 s1 的排列之一 (“ba”).
示例 2:
输入:s1= “ab” s2 = “eidboaoo”
输出:false
代码如下:
/**
* @param {string} s
* @return {number}
*/
/*
* 只使用一个数组
* 使用diff来记录变化的数据个数,当加入新数据diff++,当旧数据减小为0时diff--
* 当cnt[x]=0时,diff++,改变diff,再验证cnt[x]是否=0,若是则diff--;
* cnt[y]同理---注意y的取值为s2[i-n]---移动窗口的长度始终为n
* */
var lengthOfLongestSubstring = function(s) {
const n = s1.length, m = s2.length;
if (n > m) {
return false;
}
const cnt = new Array(26).fill(0);
for (let i=0;i<n;i++){
--cnt[s1[i].charCodeAt()-'a'.charCodeAt()];
++cnt[s2[i].charCodeAt()-'a'.charCodeAt()]
}
let diff=0;
for (const c of cnt){
if (c!==0){
diff++;
}
}
if (diff===0)return true;
for (let i=n;i<m;i++){
const x=s2[i].charCodeAt()-'a'.charCodeAt(),
y=s2[i-n].charCodeAt()-'a'.charCodeAt();
if (x===y)continue;
if (cnt[x]===0)diff++;
cnt[x]++;
if (cnt[x]===0)diff--;
if (cnt[y]===0)diff++;
cnt[y]--;
if (cnt[y]===0)diff--;
if (diff===0)return true;
}
return false;
};