438. 找到字符串中所有字母异位词
黔驴技穷,思路记录一下(虽然超时了):使用哈希表standard保存p字符串中字符极其数量,然后使用temp复制一份
然后依次读入s字符串,读入一个则减去temp中的一个,如果某一项减为0了,则放弃,从first中开始,保存每个字符串在当前扫描字符串的位置


查看代码
class Solution{
public:
vector<int> findAnagrams(string s, string p) {
vector<int>result;
int s_len = s.size();
int p_len = p.size();
int tmp_len=p_len;
if(s_len<p_len){
return result;
}
unordered_map<char,int>temp;
unordered_map<char,int>standard;
unordered_map<char,int>first;
for(int i=0;i<p_len;i++){
standard[p[i]]++;
}
temp=standard;
for(int i=0;i<s_len;i++){
//cout<<i;
if(standard.count(s[i])==0){
tmp_len = p_len;
first.clear();
temp.clear();
temp=standard;
continue;
}
if(first.count(s[i])==0){
first[s[i]] = i;
}
temp[s[i]]--;
if(temp[s[i]]<0){
tmp_len = p_len;
i=first[s[i]];
first.clear();
temp.clear();
temp=standard;
}
else{
tmp_len--;
if(tmp_len==0){
//cout<<i;
result.push_back(i-p_len+1);
i=i-p_len+1;
tmp_len = p_len;
temp.clear();
temp=standard;
first.clear();
cout<<i;
}
}
}
return result;
}
};

浙公网安备 33010602011771号