C++


  • 0
    B
    class Solution {
    public:
        bool checkInclusion(string s1, string s2) {
            unordered_map<char, int> hash;
            int cnt = 0;
            for (auto v: s1) {
                if (hash.find(v) != hash.end()) hash[v]++;
                else {hash[v]++; cnt++;}
            }
            int left = 0, right = s1.length()-1;
            for (int i = 0; i<s1.length(); i++) {
                if (hash.find(s2[i]) != hash.end()) {
                    hash[s2[i]]--;
                    if (hash[s2[i]] == 0) cnt--;
                }
            }
            if (cnt == 0) return true;
            while (right < s2.length()) {
                if (hash.find(s2[left]) != hash.end()) {
                    hash[s2[left]]++;
                    if (hash[s2[left]] == 1) cnt++;
                }
                left++; right++;
                if (hash.find(s2[right]) != hash.end()) {
                    hash[s2[right]]--;
                    if (hash[s2[right]] == 0) cnt--;
                }
                if (cnt == 0) return true;
            }
            return false;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.