其他分享
首页 > 其他分享> > LeetCode 438 Find All Anagrams in a String 滑动窗口

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;
    }
};

标签:shash,return,String,Anagrams,vector,ans,letters,ns,Find
来源: https://www.cnblogs.com/xinyu04/p/16541091.html