438. Find All Anagrams in a String

问题描述:

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

 

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

 

解题思路:

仔细读题,是让我们找,在s中p的变位词。

我一开始以为让找s内存在的所有的变位次,当时有点懵逼

这样的话可以用滑动窗口来做,移动r:

  1.当s[r] 的字符不属于 p的时候,要将l移动到r的位置,注意改变cnt

  2.当s[r]的字符属于p的时候,需要检查,当前target[s[r]]的值是否大于0,若等于0,则需要移动l到大于0为止,同样不要忘记改变cnt

  3.检查cnt是否为0,若为n,则找到变位词。

 

代码:

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> ret;
        if(s.empty())
            return ret;
        unordered_map<char, int> target;
        for(char c:p){
            target[c]++;
        }
        int l = 0;
        int r = 0;
        int cnt = p.size();
        int sLen = s.size();
        while(r < sLen){
            if(target.count(s[r]) == 0){
                while(l < r){
                    target[s[l++]]++;
                    cnt++;
                }
                r++;
                l = r;
            }else{
                if(target[s[r]] > 0){
                    target[s[r++]]--;
                    cnt--;
                }else{
                    while(l < r && target[s[r]] == 0) {
                        target[s[l++]]++;
                        cnt++;
                    }
                }
                if(cnt == 0){
                    ret.push_back(l);
                    target[s[l++]]++;
                    cnt++;
                }
            }
        }
        return ret;
    }
};

 

posted @ 2018-06-25 02:03  妖域大都督  阅读(127)  评论(0编辑  收藏  举报