LeetCode:9.找到字符串中所有的字母异位词
目录
1.找到字符串中所有的字母异位词
1.找到字符串中所有的字母异位词
这道题我们可以通过滑动窗口的思想来解决,先通过哈希表来统计字符串p中每一个字母所出现的个数,同时用另一个哈希表来统计字符串s中个字母所出现的次数,如果s中字母出现的次数小于等于p中所出现的次数,那么这就是一个有效字符,用count来统计有效字符的个数,如果当前窗口中长度大于p的长度,我们就需要出窗口,同理如果s中出现的次数小于等于p中出现的次数,说明出去了一个有效字符,count--,如果count等于p的长度,就找到了一个有效的结果
class Solution {
public:vector<int> findAnagrams(string s, string p) {int hash1[26] = { 0 };for(auto ch : p)hash1[ch - 'a']++;int hash2[26] = { 0 }, m = p.size(), n = s.size();vector<int> ret;for(int left = 0, right = 0, count = 0; right < n; right++){char in = s[right];hash2[in - 'a']++;if(hash2[in - 'a'] <= hash1[in - 'a']) count++;while(right - left + 1 > m){char out = s[left];if(hash2[out - 'a'] <= hash1[out - 'a']) count--;hash2[out - 'a']--;left++;}if(count == m) ret.push_back(left);}return ret;}
};