zoukankan      html  css  js  c++  java
  • [leedcode 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).

    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.

    public class Solution {
        public String minWindow(String s, String t) {
            //本题思路:
            //利用两个数组,以字母为下标,一个记录t中字母出现的总次数,一个记录当前搜索中已经出现字母的次数
            //处理情况:
            //1.遍历s字符串时,如果字符在t中出现,需要累计已经出现的次数,
            //2.维护一个变量count,记录当前出现了多少个合法子字符,多次重复出现的算不合法字符,
            //  如果合法字符等于子字符长度,那么就是找到一个窗口了。
            //3.找到后,需要对start重新定位
            int needTofind[]=new int[256];// 保存T中需要查找字符的个数,该数组一旦初始化完毕就不再改动 
            int hasFound[]=new int[256];// 保存S中已经找到字符的个数,该数组会动态变化 
            int minWindow=Integer.MAX_VALUE;
            String res="";
            for(int i=0;i<t.length();i++){// 初始化needToFind为需要查找字符的个数,
                needTofind[t.charAt(i)]++;
            }
            int start=0;
            int end=0;
            int count=0;
            for(;end<s.length();end++){// 用end来遍历S字符串
                if(needTofind[s.charAt(end)]==0)continue;// 表示可以忽略的字符,即除了T外的所有字符 
                char temp=s.charAt(end);// 找到一个需要找的字符
                hasFound[s.charAt(end)]++;
                if(needTofind[s.charAt(end)]>=hasFound[s.charAt(end)]) count++;// 如果找到的已经超过了需要的,就没必要继续增加count  
                if(count==t.length()){// 该窗口中至少包含了T 
                    while(needTofind[s.charAt(start)]==0||needTofind[s.charAt(start)]<hasFound[s.charAt(start)]){
                        // 压缩窗口,往后移start指针,一种情况是start指针指的都是可忽略的字符 
                        if(needTofind[s.charAt(start)]<hasFound[s.charAt(start)]){
                            // 另一种情况是已经找到字符的个数超过了需要找的个数,因此可以舍弃掉多余的部分  
                           hasFound[s.charAt(start)]--;// 舍弃掉多余的部分
                        }
                        start++; // 压缩窗口 
                    }
                    int window=end-start+1;
                    if(window<minWindow){// 保存最小窗口 
                        res=s.substring(start,end+1);
                        minWindow=window;
                        
                    }
                }
                
            }
            return res;
        }
    }
  • 相关阅读:
    AC自动机 [模板]
    ChonSu [ZOJ 2684]
    Quad Tiling [POJ 3420]
    LCA 最近公共祖先 [POJ 1330]
    强连通分量[trajan]
    高斯消元 [模板]
    01K Code [HDU 1545]
    Cycle Game [ZOJ 2686]
    清除Eclipse中的内置浏览器中的历史记录(REF)
    第三方的 NET 数据库连接提供者,Lightswitch
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4646373.html
Copyright © 2011-2022 走看看