leetcode sliding window 438 Find all letter dysphoric words in the string

THE

problem

Insert picture description here

solution

Code



/*
思路: 滑动窗口解决。  当right增加的时候更新有效数。 当尺寸>= p. size 时候进入left, left缩小的时候
判断是否是valid == p .size() , 不是的话清除left坐标在valid和window中的信息。 结果在缩小的时候更新。  
回答完这些问题之后我们确定返回的是坐标。 

- 
- 
- - 
- - 
- 
*/


class Solution {
    
    
public:
   vector<int> findAnagrams(string s, string p) {
    
    
       unordered_map<char, int> need, window;
       vector<int> ans;
       int left = 0 , right = 0, valid = 0;
       for(char c:p)need[c]++;
       while(right<s.size()){
    
    
           char temp = s[right];
           right++;
           if(need.count(temp)){
    
    
               window[temp]++;
               if(window[temp] == need[temp])
                   valid++;
           }
           while(right-left>=p.size()){
    
    

               if(valid==need.size()){
    
    
                   ans.push_back(left);
                   //valid--;
               }
               char b = s[left];
               left++;
               if(need.count(b)){
    
    
                   if(window[b]==need[b]){
    
    
                       valid--;
                   }
                   window[b]--;
               }
           }
       }
       return ans;

   }
};

Summary and reflection

  1. The basic template can be inserted.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114099492