力扣438.找到字符串中所有字母异位词
力扣438.找到字符串中所有字母异位词
vector插入用emplace_back
- push_back会构造拷贝函数
- emplace_back直接在原数组中加数 更快一些
class Solution { public: vector<int> findAnagrams(string s, string p) { int n = s.size(); int pl = p.size(); if(n < pl) return vector<int>(); vector<int> cnt1(26); vector<int> cnt2(26); for(int i=0;i<pl;i++) { cnt1[p[i]-'a'] ++; cnt2[s[i]-'a'] ++; } vector<int> ans; if(cnt1 == cnt2) ans.emplace_back(0);; for(int i=pl;i<n;i++) { cnt2[s[i-pl] - 'a'] --; cnt2[s[i] - 'a'] ++; if(cnt1 == cnt2) ans.emplace_back(i-pl+1);; } return ans; } };