Posted on

Description

Submission

class Solution {

    bool isSame(map<char, int>& m1, map<char, int>& m2) {
        for(auto& p: m1) {
            if(p.second != m2[p.first]) return false;
        }
        return true;
    }

public:
    bool checkInclusion(string s1, string s2) {
        if(s1.size() > s2.size()) return false;

        map<char, int> s1Freq, s2Freq;
        int j = 0;
        for(; j < s1.size(); ++j) {
            s1Freq[s1[j]]++;
            s2Freq[s2[j]]++;
        }
        s2Freq[s2[--j]]--;
        for(int i = 0; j < s2.size(); ++i, ++j) {
            s2Freq[s2[j]]++;
            if(isSame(s1Freq, s2Freq)) return true;
            s2Freq[s2[i]]--;
        }

        return false;
    }
};
class Solution {
    int cnt1[26];
    int cnt2[26];
public:
    bool checkInclusion(string s1, string s2) {
        int len1 = s1.length(), len2 = s2.length();
        for(char ch: s1) {
            ++cnt1[ch-'a'];
        }

        for(int i = 0, j = 0; j < len2; ++j) {
            ++cnt2[s2[j]-'a'];

            if(j - i + 1 == len1) {
                bool flag = true;
                for(int j = 0; j < 26; ++j) {
                    if(cnt1[j] != cnt2[j]) {
                        flag = false;
                        break;
                    }
                }
                if(flag) return true;

                --cnt2[s2[i]-'a'];
                ++i;
            }
        }   

        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *