程式語言 - LeetCode - C++ - 567. Permutation in String



題目:


解答:

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        vector<int> c1(26, 0);
        vector<int> c2(26, 0);

        for (char c : s1) {
            c1[c - 'a'] += 1;
        }

        int n = s1.size();
        int m = s2.size();

        for (int i = 0; i < m; ++i) {
            c2[s2[i] - 'a'] += 1;

            if (i >= n) {
                c2[s2[i - n] - 'a'] -= 1;
            }

            if (c1 == c2) {
                return true;
            }
        }

        return false;
    }
};