题目描述
给定两个字符串 s 和 p,找到 s 中所有 p 的 变位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
变位词 指字母相同,但排列不同的字符串。
(和Offer II 014 一个思路,找到一个数组后把左边界+1继续寻找即可)
代码
#include<hash_map>
using namespace __gnu_cxx;
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
hash_map<char,int> hashmap;
for(int i=0;i<26;i++){
hashmap.insert(make_pair('a'+i,0));
}
for(int i=0;i<p.length();i++){
hashmap[p[i]]++;
}
hash_map<char,int> tempmap(hashmap);
int left = 0,right = 0,count = p.length(),flag = 0;
vector<int> result;
while(right < s.length()){
if(flag == 0){
hash_map<char,int> tempmap(hashmap);
flag=1;
}
if(tempmap[s[right]] == 0){
if(left < right){
tempmap[s[left]]++;
left++;
count++;
}
else{
left++;
right++;
}
}
if(tempmap[s[right]]!=0){
tempmap[s[right]]--;
right++;
count--;
if(count == 0){
result.push_back(left);
tempmap[s[left]]++;
left++;
count++;
}
}
}
return result;
}
};