438. 找到字符串中所有字母异位词
This commit is contained in:
29
test009.cpp
Normal file
29
test009.cpp
Normal file
@@ -0,0 +1,29 @@
|
||||
class Solution {
|
||||
public:
|
||||
bool checkCnt(vector<int>& cnts, vector<int>& cntp){
|
||||
for(int i = 0; i < 26; i++){
|
||||
if(cnts[i] != cntp[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
vector<int> findAnagrams(string s, string p) {
|
||||
vector<int> cntp(26);
|
||||
for(char c:p){ cntp[c-'a']++; }
|
||||
|
||||
vector<int> ret;
|
||||
vector<int> cnts(26);
|
||||
for(int i = 0; i < min(p.length(), s.length()); i++){
|
||||
cnts[s[i] - 'a']++;
|
||||
}
|
||||
|
||||
if(checkCnt(cnts, cntp)) { ret.push_back(0);}
|
||||
|
||||
for(int r = p.length(); r < s.length(); r++){
|
||||
int l = r - p.length() + 1;
|
||||
cnts[s[l-1] - 'a']--;
|
||||
cnts[s[r] - 'a']++;
|
||||
if(checkCnt(cnts, cntp)) { ret.push_back(l); }
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user