LeetCode每日一题:438. 找到字符串中所有字母异位词【2021/11/28】

198 阅读1分钟

题目链接:438. 找到字符串中所有字母异位词 - 力扣(LeetCode) (leetcode-cn.com)

难度:Medium

同时移动两个指针,间隔 p.size()p.size()。维护一个 mapmap,如果 ss 在这个区间内的字符次数和 pp 相同,则满足异位词。

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> ans;
        int len1 = s.size();
        int len2 = p.size();
        if(len2 > len1){
            return ans;
        }
        unordered_map<int,int>m1;
        unordered_map<int,int>m2;
        for(int i=0;i<len2;i++){
            m1[p[i]-'a']++;
            m2[s[i]-'a']++;
        }
        int l = 0,r = len2-1;
        while(r<len1){
            if(m1==m2){
                ans.push_back(l);
            }
            if(m2[s[l]-'a'] == 1){
                m2.erase(s[l]-'a');
            } else {
                m2[s[l]-'a']--;
            }
            l++;
            m2[s[++r]-'a']++;
        }
        return ans;
    }
};