zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    难度:90    String问题里面有很多不好做的,动不动就DP什么的,参考了一些资料http://blog.csdn.net/fightforyourdream/article/details/17373203

    For example,
    S = “ADOBECODEBANC”
    T = “ABC”
    Minimum window is “BANC”.

    Thoughts:
    The idea is from here. I try to rephrase it a little bit here. The general idea is that we find a window first, not necessarily the minimum, but it’s the first one we could find, traveling from the beginning of S. We could easily do this by keeping a count of the target characters we have found. After finding an candidate solution, we try to optimize it. We do this by going forward in S and trying to see if we could replace the first character of our candidate. If we find one, we then find a new candidate and we update our knowledge about the minimum. We keep doing this until we reach the end of S. For the giving example:

      1. We start with our very first window: “ADOBEC”, windowSize = 6. We now have “A”:1, “B”:1, “C”:1 (保存在needToFind数组里)
      2. We skip the following character “ODE” since none of them is in our target T. We then see another “B” so we update “B”:2. Our candidate solution starts with an “A” so getting another “B” cannot make us a “trade”. (体现在代码就是只有满足hasFound[S.charAt(start)] > needToFind[S.charAt(start)]) 才能移动左指针start)
      3. We then see another “A” so we update “A”:2. Now we have two “A”s and we know we only need 1. If we keep the new position of this “A” and disregard the old one, we could move forward of our starting position of window. We move from A->D->O->B. Can we keep moving? Yes, since we know we have 2 “B”s so we can also disregard this one. So keep moving until we hit “C”: we only have 1 “C” so we have to stop. Therefore, we have a new candidate solution, “CODEBA”. Our new map is updated to “A”:1, “B”:1, “C”:1.
      4. We skip the next “N” (这里忽略所有不在T的字符:用needToFind[S.charAt(start)] == 0来判断) and we arrive at “C”. Now we have two “C”s so we can move forward the starting position of last candidate: we move along this path C->O->D->E until we hit “B”. We only have one “B” so we have to stop. We have yet another new candidate, “BANC”.
      5. We have hit the end of S so we just output our best candidate, which is “BANC”.

    底下这个做法看似简单,其实里面各种精巧的设计啊:先找到满足条件的一个window(不一定是最优),每次移动右窗口,吸纳一个新元素进去,如果不是目标元素就跳过continue,如果是的话,hasFound数组对应位置值+1,然后看能不能优化窗口大小 by 看能不能移动左窗口,移动条件就是:始终保证窗口里面含有一个T的所有必要元素(个数要保证),直到移不动为止(再移就无法保证一个完整T的各元素个数了),这时就找到一个新的window,看是否最优。

     1 public class Solution {
     2     public String minWindow(String S, String T) {
     3         int[] hasFound = new int[256];
     4         int[] needtoFind = new int[256];
     5         for (int i=0; i<T.length(); i++) {
     6             needtoFind[(int)(T.charAt(i)-'')]++;
     7         }
     8         int count = 0;
     9         int start = 0;
    10         int end = 0;
    11         String minWindow = "";
    12         int minWinSize = Integer.MAX_VALUE;
    13         for (; end<S.length(); end++) {
    14             if (needtoFind[(int)(S.charAt(end)-'')] == 0) continue;
    15             char c = S.charAt(end);
    16             hasFound[(int)(c-'')]++;
    17             if (hasFound[(int)(c-'')] <= needtoFind[(int)(c-'')]) {
    18                 count++;
    19             }
    20             if (count == T.length()) { //the current window contains at least T, optimize the window now
    21                 while (needtoFind[S.charAt(start)]==0 || hasFound[S.charAt(start)]>needtoFind[S.charAt(start)]) {
    22                     if (hasFound[S.charAt(start)] > needtoFind[S.charAt(start)]) {
    23                         hasFound[S.charAt(start)]--;
    24                     }
    25                     start++;
    26                 }
    27                 if (end-start+1 < minWinSize) {
    28                     minWinSize = end - start + 1;
    29                     minWindow = S.substring(start, end+1);
    30                 }
    31             }
    32         }
    33         return minWindow;
    34     }
    35 }

    在处理字符串时候用数组比Hashtable要来的方便, 当然这道题也可用HashMap来做:

     1 class Solution {
     2     public String minWindow(String s, String t) {
     3         if (s == null || s.length() == 0 || t == null || t.length() == 0 ) return "";
     4         HashMap<Character, Integer> target = new HashMap<>();
     5         for (int i = 0; i < t.length(); i ++) {
     6             target.put(t.charAt(i), target.getOrDefault(t.charAt(i), 0) + 1);
     7         }
     8         
     9         int l = 0, r = 0, minLen = Integer.MAX_VALUE;
    10         String res = "";
    11         HashMap<Character, Integer> actual = new HashMap<>();
    12         
    13         int count = 0;
    14         
    15         for (; r < s.length(); r ++) {
    16             char cur = s.charAt(r);
    17             actual.put(cur, actual.getOrDefault(cur, 0) + 1);
    18             if (actual.get(cur) <= target.getOrDefault(cur, 0)) count ++;
    19             
    20             if (count < t.length()) continue;
    21             
    22             //shrink left edge
    23             while (l <= r && actual.get(s.charAt(l)) > target.getOrDefault(s.charAt(l), 0)) {
    24                 actual.put(s.charAt(l), actual.get(s.charAt(l)) - 1);
    25                 l ++;
    26             }
    27             
    28             if (minLen > r - l + 1) {
    29                 minLen = r - l + 1;
    30                 res = s.substring(l, r + 1);
    31             }
    32         }
    33         
    34         return res;
    35     }
    36 }

    Here's a Window solving template. 

     1 for (; r < s.length(); r ++) {
     2             char cur = s.charAt(r);
     3             //add to some collection
     4             
     5             //shrink left edge
     6             while (l <= r && r - l > someCondition)) {
     7                 l ++;
     8             }
     9             // [l, r] is currently a valid window 
    10             if (minLen > r - l + 1) {
    11                 minLen = r - l + 1;
    12                 res = s.substring(l, r + 1);
    13             }
    14         }
  • 相关阅读:
    解决U3D4.1.5或以上无法启动MONODEV的方法
    unity的List构造函数在IOS平台存在缺陷
    【Python爬虫】性能提升
    【JavaScript+jQuery】JavaScript权威指南读书笔记1
    【Python爬虫】爬虫的基本修养
    【Python基础】Python yield 用法
    【Python进阶】回调函数
    【Python基础】Python输出终端的颜色显示
    【python进阶】并发编程-线程进程协程
    【项目实战开发】密码加密处理后登录验证
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4007886.html
Copyright © 2011-2022 走看看