• Minimum Window Substring


    Description:

    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).

    For example,
    S = "ADOBECODEBANC"
    T = "ABC"

    Minimum window is "BANC".

    Note:
    If there is no such window in S that covers all characters in T, return the emtpy string "".

    If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

    Code:

    struct record
    {
        int start, end, length;
        record(){
            start=end=length = 0;
        }
    };
    class Solution {
    public:
        bool isWindowContainT(int * win, int * ch_t)
        {
            for (int i = 0; i < 256; ++i)
            {
                if (win[i] < ch_t[i])
                    return false;
            }
            return true;
        }
        string minWindow(string s, string t) {
            unsigned int lengthS = s.size();
            unsigned int lengthT = t.size();
            if (lengthT > lengthS)
                return "";
                
            int ch_t[256], ch_win[256];
            for (int i = 0; i < 256; ++i)
            {
                ch_t[i] = 0;
                ch_win[i] = 0;
            }
            for (int i = 0; i < lengthT; ++i)
                ch_t[t[i]]++;
                
            int start = 0, end = 0;
            ch_win[s[0]]=1;
            record min;
            min.length = INT_MAX;
            bool flag = false;
            while (end < lengthS)
            {
                if ( isWindowContainT(ch_win, ch_t) )
                {
                     flag = true;
                    if (end-start+1 < min.length)
                    {
                        min.start = start;
                        min.end = end;
                        min.length = end-start+1;
                    }
                    ch_win[s[start]]--;
                    start++;
                }
                else
                {
                    ch_win[s[++end]]++;
                }
            }
            if (flag)
                return s.substr(min.start, min.end-min.start+1);
            else
                return "";
        }
    };

    注意:T中允许字符重复

    思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的

  • 相关阅读:
    centos7刚安装解决网络问题
    python matplotlib的常用绘图方法
    python实现最小可编辑距离
    JDBC快速入门
    关于MYSQL常用操作查询语言
    3w字详解java集合
    ELK实时日志分析平台环境部署--完整记录(转)
    ELK简介(转)
    python格式化输出(% & format)
    ElasticSearch查询 搜索 | 更新 | 查询
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4778667.html
Copyright © 2020-2023  润新知