8 lines concise c++ solution using sliding window


  • 0

    The idea is to use two sliding windows to store the characters of s1 and the same size of s2, respectively.

    bool checkInclusion(string s1, string s2) {
            int m = s1.size(), n = s2.size();
            vector<int> w1(26,0), w2(26,0);
            for(int i=0; i<m; i++){w1[s1[i]-'a']++, w2[s2[i]-'a']++;}
            for(int i = m; i<n; i++){
                if(w1==w2)return true;
                w2[s2[i-m]-'a']--, w2[s2[i]-'a']++;
            }
            return (w1==w2);
        }
    

  • 0

    Thank you for watching!


Log in to reply
 

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