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”.
在字符串里寻找所有颠倒字母顺序子串,开始我想这用暴力枚举法,时间复杂度是O(m*n),结果超时了。
class Solution {
public:
vector<int> findAnagrams(string s, string p)
{
int i;
vector<int>ret;
if(s.size()<p.size())
return ret;
sort(p.begin(),p.end());
for(i=0;i<=s.size()-p.size();i++)
{
string t=s.substr(i,p.size());
sort(t.begin(),t.end());
if(p==t)
ret.push_back(i);
}
return ret;
}
};
第二种方法:利用hash映射,用两个指针维护一个窗口,时间复杂度O(n)
class Solution
{
public:
vector<int> findAnagrams(string s, string p)
{
int i,j;
map<char,int>pmap;
for(i=0;i<p.size();i++)
pmap[p[i]]++;
int count=0;
int index=0;
vector<int>ret;
for(i=0;i<s.size();)
{
if(count==p.size())
{
ret.push_back(index);
pmap[s[index]]++;
index++;
count--;
}
else
{
if(pmap.find(s[i])==pmap.end())
{
for(j=index;j<=i;j++)
{
if(pmap.find(s[j])!=pmap.end())
{
pmap[s[j]]++;
count--;
}
}
i++;
index=i;
}
else
{
--pmap[s[i]];
if(pmap[s[i]]>=0)
count++;
else
{
while(pmap[s[i]]<0)
{
pmap[s[index]]++;
index++;
}
}
i++;
}
}
//cout<<pmap['a']<<' '<<pmap['b']<<' '<<pmap['c']<<endl;
}
if(count==p.size())
ret.push_back(index);
return ret;
}
};