xinyu04

导航

LeetCode 438 Find All Anagrams in a String 滑动窗口

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An \(Anagram\) is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solution

我们用滑动窗口即可,注意 \(vector\) 可以直接比较是否相等

点击查看代码
class Solution {
private:
    vector<int> ans;
    
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> phash(26,0);
        vector<int> shash(26,0);
        int ns =  s.length(), np = p.length();
        if(ns<np) return ans;
        int l=0, r = np-1;
        for(int i=l;i<=r;i++){
            phash[p[i]-'a']++;shash[s[i]-'a']++;
        }
        if(phash==shash)ans.push_back(l);
        while(r<ns){
            r++;
            if(r>=ns)break;
            shash[s[r]-'a']++;
            shash[s[l]-'a']--;l++;
            if(shash==phash)ans.push_back(l);
        }
        return ans;
    }
};

posted on 2022-08-01 17:28  Blackzxy  阅读(16)  评论(0编辑  收藏  举报