zoukankan      html  css  js  c++  java
  • **Minimum Window Substring & String类问题模板

    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 empty string "".

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

    牛逼的讨论:无法理解的大牛思路

    https://leetcode.com/discuss/72701/here-10-line-template-that-can-solve-most-substring-problems

    另一个讲解:正常人可以懂的思路

    http://www.cnblogs.com/TenosDoIt/p/3461301.html

    public class Solution {
    public String minWindow(String S, String T) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int lens = S.length(), lent = T.length();
            int[] srcCnt = new int[256] ;//T中每个字母的个数
            int[] foundCnt = new int[256] ;//当前找到T中每个字母的个数
            char[] SS = S.toCharArray();
            char[] TT = T.toCharArray();
            for(int i = 0; i < lent; i++)
                srcCnt[TT[i]]++;
            int hasFound = 0;//已经找到的字母数目
            int winStart = -1, winEnd = lens;//窗口的左右边界
            //两个指针start和i一起扫描
            for(int i = 0, start = 0; i < lens; i++)
                if(srcCnt[SS[i]] != 0)
                {
                    foundCnt[SS[i]]++;
                    if(foundCnt[SS[i]] <= srcCnt[SS[i]])hasFound++;
                    if(hasFound == lent)
                    {//找到了一个满足的窗口
                        while(srcCnt[SS[start]] == 0 ||
                              foundCnt[SS[start]] > srcCnt[SS[start]])
                              //当S[start]不在T中,或者找到的S[start]个数大于T中S[start]个数,缩减窗口
                        {
                            if(srcCnt[SS[start]] != 0)
                                foundCnt[SS[start]]--;
                            start++;
                        }
                        if(winEnd - winStart > i - start)
                        {
                            winStart = start;
                            winEnd = i;
                        }
                        foundCnt[SS[start]]--;
                        start++;
                        hasFound--;
                    }
                }
            return winStart != -1 ? S.substring(winStart, winEnd+1) : "";
        }
    }
  • 相关阅读:
    7.Pod控制器—Job&CronJob
    6.Pod控制器—DaemonSet
    5.Pod控制器—ReplicaSet&Deployment
    0.4kubeadm参数说明
    14.Open vSwitch实现跨主机的容器之间网络互联
    p1144_最短路计数问题
    vue在dom绑定点击事件后,同时将值和事件传递
    vue中使用lodash的throttle不生效解决方案
    vuecli3项目添加pwa支持
    flutter for web跨域解决方案
  • 原文地址:https://www.cnblogs.com/hygeia/p/5133265.html
Copyright © 2011-2022 走看看