[滑动窗口/哈希] leetcode 567 Permutation in String

problem:https://leetcode.com/problems/permutation-in-string/

        这道题感觉几乎和Leetcode上另一题一模一样,昨天刚刷的:https://www.cnblogs.com/fish1996/p/11269526.html,就当签到题爽一爽了。

class Solution {
public:
    bool checkInclusion(string s1, string s2) {

        vector<int> target(26, 0);
        for (int i = 0; i < s1.size(); i++)
        {
            target[s1[i] - 'a']++;
        }

        int k = s1.size();

        vector<int> source(26, 0);
        int count = 0;
        for (int i = 0; i < s2.size(); i++)
        {
            source[s2[i] - 'a']++;
            if (source[s2[i] - 'a'] <= target[s2[i] - 'a'])
            {
                count++;
            }

            if (i >= k)
            {        
                if (source[s2[i - k] - 'a'] <= target[s2[i - k] - 'a'])
                {
                    count--;
                }
                source[s2[i - k] - 'a']--;
            }

            if (count == k)
            {
                return true;
            }
        }

        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11279050.html
567