xinyu04

导航

LeetCode 567 Permutation in String Map

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

Solution

直接用两个map分别存储 \(s1\)和与 \(s1\)相同长度的 \(s2\) 子串。 比较的话,直接用 \(=\) 即可。对于数量为 \(1\) 的字符,我们用 \(map.erase\) 不能直接 \(map[c]-1\)

点击查看代码
class Solution {
private:
    map<char,int> mp, str1_mp;
    int l,r;
    
    bool check(map<char,int> str1_mp, map<char,int> mp){
        if(mp==str1_mp)return true;
        return false;
    }
    
    
public:
    bool checkInclusion(string s1, string s2) {
        int n1 = s1.length();
        int n2 = s2.length();
        if(n2<n1)return false;
        l=0; r=n1-1;
        for(int i=0;i<n1;i++)mp[s2[i]]+=1, str1_mp[s1[i]]+=1;
        if(mp==str1_mp)return true;
        for(r = n1;r<n2;r++){
            
            if(mp[s2[l]]==1)mp.erase(s2[l]);
            else mp[s2[l]]--;
            l++;mp[s2[r]]++;
            if(mp==str1_mp)return true;
        }
        return false;
    }
};

posted on 2022-07-20 17:08  Blackzxy  阅读(15)  评论(0编辑  收藏  举报