力扣438.找到字符串中所有字母异位词

作者 : admin 本文共458个字,预计阅读时间需要2分钟 发布时间: 2024-06-4 共3人阅读

力扣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;
          }
      };
    
本站无任何商业行为
个人在线分享 » 力扣438.找到字符串中所有字母异位词
E-->