滑动窗口 leetcode 76

Problem: 76. 最小覆盖子串

思路

第一次遇到不看题解我是写不出来,主要是ans是不断变化的

解题方法

用两个指针,left缩小区间,right扩大区间,直到产生冗余元素开始,缩减left,直到不能再缩减为止,取满足的最小字串就好了

复杂度

时间复杂度:

\(O(n)\)

空间复杂度:

\(O(n_1)\)

Code

class Solution {
public:
    string minWindow(string s, string t) {
      string ans=s+t;
      int n1=s.size(),n2=t.size(),left=0,count=0;
      map<char,int> tmap;
      map<char,int> smap;
      for (size_t i = 0; i <n2; i++)
      {
        tmap[t[i]]++;
      }
      for (int right = 0; right < n1; right++)
      {
        smap[s[right]]++;
        if(tmap[s[right]]>=smap[s[right]]) count++;
        while (left<right&&smap[s[left]]>tmap[s[left]])
        {
          smap[s[left]]--;
          left++;
        }
        if(count==n2){
          if(right-left+1<ans.size())
          ans=s.substr(left,right-left+1);
        } 
      }
      return ans==s+t?"":ans;
    }
};
posted @ 2024-02-16 16:38  oxidationreaction  阅读(16)  评论(0)    收藏  举报