Problem: 438. 找到字符串中所有字母异位词
文章目录
- 题目描述
- 思路及解法
- 复杂度
- Code
题目描述
思路及解法
1.编写辅助函数bool same(vector& need, vector& matched):
1.1 以need为标准,循环对比need和matched的每一个位置的元素值是否相等
2.获取s和p的长度,lenS和lenP;
3.创建vector needs(26,0);,将p中的字符映射到其中needs[p[i] - ‘a’]++;
4.创建窗口:创建vector matched(26,0);,并定义指针starP、endP,并且将字符串s中的前lenP个字符映射到matched中,并调用same进行一次判断,若满足则将startP添加到结果集合result中
5.维护窗口:当两个指针均小于lenS时执行**matched[s[starP] - ‘a’]–;matched[s[endP] - ‘a’]++;**并且让startP与endP自增,并调用same函数,将字母异位置词的起始位置添加到result中
复杂度
时间复杂度:
O ( 1 ) O(1) O(1)
空间复杂度:
O ( 1 ) O(1) O(1)
Code
class Solution {
public:
/**
* Sliding window
*
* @param s The string given to be matched
* @param p Substring
* @return vector<int>
*/
vector<int> findAnagrams(string s, string p) {
int sLen = s.length();
int pLen = p.length();
if (pLen > sLen) {
return {};
}
vector<int> needs(26,0);
for (int i = 0; i < pLen; ++i) {
needs[p[i] - 'a']++;
}
vector<int> matched(26,0);
int starP = 0;
int endP = 0;
vector<int> result;
while (endP < pLen) {
matched[s[endP] - 'a']++;
endP++;
}
if (same(needs, matched)) {
result.push_back(starP);
}
while (starP < sLen && endP < sLen) {
matched[s[starP] - 'a']--;
matched[s[endP] - 'a']++;
starP++;
endP++;
if (same(needs, matched)) {
result.push_back(starP);
}
}
return result;
}
private:
/**
*Determines whether the values in two arrays (within a given range) are equal
*
* @param need Judgment reference array
* @param matched Array to match each time
* @return bool
*/
bool same(vector<int>& need, vector<int>& matched) {
for (int i = 0; i < need.size(); ++i) {
if (need[i] != matched[i]) {
return false;
}
}
return true;
}
};