网站如何申请微信支付,百度网站地图怎么做,网站开发职业规划,企业为什么做平台网站Problem: 438. 找到字符串中所有字母异位词 文章目录 题目描述思路及解法复杂度Code 题目描述 思路及解法 1.编写辅助函数bool same(vector need, vector matched)#xff1a; 1.1 以need为标准#xff0c;循环对比need和matched的每一个位置的元素值是否相等 2.获… 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 vectorint*/vectorint findAnagrams(string s, string p) {int sLen s.length();int pLen p.length();if (pLen sLen) {return {};}vectorint needs(26,0);for (int i 0; i pLen; i) {needs[p[i] - a];}vectorint matched(26,0);int starP 0;int endP 0;vectorint 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(vectorint need, vectorint matched) {for (int i 0; i need.size(); i) {if (need[i] ! matched[i]) {return false;}}return true;}
};