zoukankan      html  css  js  c++  java
  • 76. Minimum Window Substring

    问题描述:

    Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

    Example:

    Input: S = "ADOBECODEBANC", T = "ABC"
    Output: "BANC"
    

    Note:

    • If there is no such window in S that covers all characters in T, return the empty string "".
    • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

    解题思路:

    这道题我们可以用滑动窗口来解决。

    首先我们先将t中的字符放到hashmap中,对应的是字符和它出现的次数。

    然后我们遍历s,并用滑动窗口来寻找最短的子串。

    首先向窗口里加入字符,即移动right。

    在移动right的途中,遇见存在于t中的字符,对map中t的出现次数-1,并且当map[s[right]] > 0 时对总计数count+1。

    当count与t.size()相等时,说明当前窗口[left, right]中包括了t中所有的字符,我们可以尝试移动left来去掉当前窗口中不属于t中的字符串,并且更新返回字符串ret。

    若当前字符是t中的字符串,我们需要对m中该字符串出现的次数+1,若此时m[s[left]] > 0 说明移走了t中的字符串,当前窗口不包含t中所有字符,count需要-1。

    再继续移动right

    代码:

    class Solution {
    public:
        string minWindow(string s, string t) {
            if(t.size() > s.size())
                return "";
            unordered_map<char, int> m;
            for(char c : t){
                m[c]++;
            }
            int left = 0;
            int minLen = s.size()+1;
            int count = 0;
            string ret;
            for(int i = 0; i < s.size(); i++){
                if(m.count(s[i])){
                    m[s[i]]--;
                    if(m[s[i]] >= 0)
                        count++;
                    while(count == t.size()){
                        if((i - left + 1) < minLen){
                            minLen = i - left + 1;
                            ret = s.substr(left, minLen);
                        }
                        if(m.count(s[left]) != 0){
                            m[s[left]]++;
                            if(m[s[left]] > 0)
                                count--;
                        }
                        left++;
                    }
                }
            }
            return ret;
        }
    };
  • 相关阅读:
    Fiddler 只看指定URL请求
    WTM框之—调整默认的删除方法
    WTM框之—调整grid的每页显示行数
    WTM框之—数据列表上添加按钮的学习记录
    Armbian欢迎信息系统状态脚本
    Shell中的${xxx%% *}字符串分割方法
    强制SSH使用密钥认证禁止密码登录
    Linux开机自动挂载外接存储
    mysql实现name姓名多个相同的数据只取一条
    git 常用命令备忘录
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9175919.html
Copyright © 2011-2022 走看看