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".

解法:

 1 class Solution {
 2 public:
 3     vector<int> findAnagrams(string s, string p) {
 4         unordered_map<char,int> freq;
 5         vector<int> result;
 6         if(p.size()>s.size()){
 7             return result;
 8         }
 9         for(int i=0;i<p.size();i++){
10             freq[p[i]]++;
11             freq[s[i]]--;
12             if(freq[s[i]]==0){
13                 freq.erase(s[i]);
14             }
15             if(freq[p[i]]==0){
16                 freq.erase(p[i]);
17             }
18             
19         }
20         
21         if(freq.size()==0){
22             result.push_back(0);
23         }
24         for(int i=p.size();i<s.size();i++){
25             freq[s[i]]--;
26             freq[s[i-p.size()]]++;
27             if(freq[s[i]]==0){
28                 freq.erase(s[i]);
29             }
30             if(freq[s[i-p.size()]]==0){
31                 freq.erase(s[i-p.size()]);
32             }
33             if(freq.size()==0){
34                 result.push_back(i-p.size()+1);
35             }
36         }
37         
38         return result;
39     }
40 };

 

 
 
posted @ 2018-12-31 06:06  回到明天  阅读(92)  评论(0编辑  收藏  举报