力扣题解---567. 字符串的排列

分类:力扣题解

  1. 字符串的排列

给你两个字符串 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;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值