Find all anagrams in a string

link link

official solution

class Solution {
    
    
public:
    vector<int> findAnagrams(string s, string p) {
    
    
        int sLen = s.size(), pLen = p.size();

        if (sLen < pLen) {
    
    
            return vector<int>();
        }

        vector<int> ans;
        vector<int> count(26);
        for (int i = 0; i < pLen; ++i) {
    
    
            ++count[s[i] - 'a'];
            --count[p[i] - 'a'];
        }

        int differ = 0;
        for (int j = 0; j < 26; ++j) {
    
    
            if (count[j] != 0) {
    
    
                ++differ;
            }
        }

        if (differ == 0) {
    
    
            ans.emplace_back(0);
        }

        for (int i = 0; i < sLen - pLen; ++i) {
    
    
            if (count[s[i] - 'a'] == 1) {
    
      // 窗口中字母 s[i] 的数量与字符串 p 中的数量从不同变得相同
                --differ;
            } else if (count[s[i] - 'a'] == 0) {
    
      // 窗口中字母 s[i] 的数量与字符串 p 中的数量从相同变得不同
                ++differ;
            }
            --count[s[i] - 'a'];

            if (count[s[i + pLen] - 'a'] == -1) {
    
      // 窗口中字母 s[i+pLen] 的数量与字符串 p 中的数量从不同变得相同
                --differ;
            } else if (count[s[i + pLen] - 'a'] == 0) {
    
      // 窗口中字母 s[i+pLen] 的数量与字符串 p 中的数量从相同变得不同
                ++differ;
            }
            ++count[s[i + pLen] - 'a'];
            
            if (differ == 0) {
    
    
                ans.emplace_back(i + 1);
            }
        }

        return ans;
    }
};


  1. The process of finding the count array, if it is me, may first find two word frequency arrays separately, and then subtract them
for(int i=0;i<plen;++i){
    
    
	s_occ[s[i]-'a']++;
	p_occ[p[i]-'a']++;
}
for(int i=0;i<26;++i){
    
    
	count[i]=s_occ[i]-p_occ[i];
}

The official method, advantages: save space, no need for additional arrays to store word frequency; save time, no need for additional loops to calculate the difference.

 for (int i = 0; i < pLen; ++i) {
    
    
            ++count[s[i] - 'a'];
            --count[p[i] - 'a'];
        }
  1. Add elements to vector
    I use push_back(), official useemplace_back()

  2. The setting of the differ variable, first of all, the meaning of diifer is to record the number of different letters in the current window and the string p, which is the number of different letters, which is very good, windows contains 5 a, and p contains only 3 a's and 4 a's in the window have the same impact on differ. I only care about whether the word frequency of the letters is the same, no, differ+1, yes, differ-1, and don't care about the specific What is the difference in word frequency, so only when the count changes between the numbers {0, 1, -1}, the difference may change.
    insert image description here

Guess you like

Origin blog.csdn.net/m0_51312071/article/details/132557148