LeetCode 76. Minimum Window Substring

news/2024/5/20 6:31:01 标签: 双指针, 滑动窗口

原题目:https://leetcode-cn.com/problems/minimum-window-substring/

 

思路:

滑动窗口的题目使用双指针的套路,一个指针用来扩大窗口,另一个指针用来缩小窗口。每一个时刻都只有一个指针移动,

本题之中,如果窗口不包含t的所有字母,进行窗口扩大,直到包含。

如果包含t中所有的 字母,进行窗口缩小,直到不包含。

记录最小len的left的位置就可以了

 

代码:

class Solution {
public:
    unordered_map<char,int> ori,cnt;
    bool check(){
        for(const auto&p:ori){
            if(cnt[p.first]<p.second){
                return false;
            }
        }
        return true;
    }
    string minWindow(string s, string t) {
        for(const char&p : t){
            ori[p]++;
        }
        int l=0,r=-1;
        int len = INT_MAX,left=-1;
        while(r<int(s.size())){
            if(ori.find(s[++r])!=ori.end()){
                cnt[s[r]]++;
            }
            while(check()&&l<=r){
                if(r-l+1<len){
                    left=l;
                    len = r-l+1;
                }
                if(ori.find(s[l])!=ori.end()){
                    cnt[s[l]]--;
                }
                ++l;
            }
        }
        return left==-1? "":s.substr(left,len);
    }
};

 


http://www.niftyadmin.cn/n/899204.html

相关文章

大话android之Activity生命周期

此为android的生命周期图&#xff0c;准确的说是activity生命周期&#xff0c; 当程序刚开始运行的时候&#xff0c;执行的是onCreat方法&#xff0c;紧接着是onStart方法和onResume方法。 当程序退回到桌面的时候&#xff0c;执行的是onPause方法和onStop方法&#xff0c;这…

LeetCode 12. Integer to Roman

原题目&#xff1a;https://leetcode-cn.com/problems/integer-to-roman/ 思路&#xff1a; 使用hash存储字符对应的数字&#xff08;从大到小排列&#xff09;&#xff0c;然后应用贪心法&#xff08;每次把最大的数字减到不能再减&#xff09;&#xff0c;从左向右进行扫描&…

大话android之简单的参数传递

参数传递&#xff0c;顾名思义就是把参数传送给其他对象&#xff0c;有了参数传递这个功能使得安卓程序开发越来越灵活。 下面是代码 首先是第一个activity中的代码 <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:tools&qu…

LeetCode 13. Roman to Integer

原题目&#xff1a;https://leetcode-cn.com/problems/roman-to-integer/ 思路&#xff1a; 观察字符序列&#xff0c;发现只要是4,9,40,90,400,900。两个字母前面的都比后面的小&#xff0c;并且后面字母代表的数字减去前面字母代表的数字就是数字的值。所以从左向右遍历&…

大话android之Bundle传递参数

bundle可以理解为是一个打包的类&#xff0c;可以装各种类型的数据&#xff0c;字符串 int数据类型 &#xff0c;Bundle类用作携带数据&#xff0c;它类似于Map&#xff0c;用于存放key-value名值对形式的值。相对于Map&#xff0c;它提供了各种常用类型的putXxx()/getXxx()方…

LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60

原题目&#xff1a;https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 思路&#xff1a; 用数组m记录time[i]%60的个数&#xff0c;每次对time[i]做判断&#xff0c;如果time[i]%60 &#xff01; 0&#xff0c;那么久在m里面找60-time[…

大话android之传递值对象(1)----serializable篇

传递值对象&#xff0c;顾名思义就是将值对象进行交互&#xff0c;所实现的接口一般有两个&#xff0c;serializable跟Parcelable&#xff0c; serializable是Java内置的序列话接口&#xff0c;它是全自动的实现简单方便。 360问答解释的serializable&#xff1a;继承了seria…

LeetCode 1025. Divisor Game

原题目&#xff1a;https://leetcode-cn.com/problems/divisor-game/ 思路&#xff1a; 如果a拿到奇数&#xff0c;那么根据奇数的因数只能是奇数&#xff0c;所以b拿到的只能是偶数。这时候只要减一&#xff0c;那么b就会给a一个奇数&#xff0c;从而b保证自己拿到的都是偶数…