leetcode-438. 找到字符串中所有字母异位词

 

class Solution {
public:

    bool check(int s[], int p[]) {
        for (int i = 0; i < 26; i++) {
            if (s[i] != p[i]) {
                return false;
            }
        }
        return true;
    }

    vector<int> findAnagrams(string s, string p) {
        vector<int> res;
        int n = s.size();
        int m = p.size();

        if(n==0||n<m)
            return res;

        int s_cnt[26] = { 0 };
        int p_cnt[26] = { 0 };

        for(int i = 0; i < p.size(); i++){
            p_cnt[p[i]-'a']++;
            s_cnt[s[i]-'a']++;
        }
        if(check(p_cnt,s_cnt)){  // c++中没有直接比较两个数组是否相等的函数,只能自己造轮子
            // cout<<"fag:"<<endl;
            res.push_back(0);
        }
            
        
        for(int i = p.size(); i < s.size(); i++){
            s_cnt[s[i-m]-'a']--;
            s_cnt[s[i]-'a']++;
            if(check(p_cnt,s_cnt)){
                res.push_back(i-m+1);
            }
        }
        return res;
    }
};

 

posted @ 2021-07-27 18:29  三一一一317  阅读(41)  评论(0)    收藏  举报