zoukankan      html  css  js  c++  java
  • [leetcode]Minimum Window Substring

    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.

    算法思路:窗口移动法。 详见这里

    本题算法略吊,还是看详解吧。

    代码如下:

     1 public class Solution {
     2     public String minWindow(String s, String t) {
     3         if(s == null || t == null) return "";
     4         int[] found = new int[256];
     5         int[] needToFind = new int[256];
     6         for(int i = 0; i < t.length(); i++){
     7             needToFind[t.charAt(i)]++;
     8         }
     9         int start = 0, count = 0,minWin = Integer.MAX_VALUE;
    10         String res = "";
    11         for(int i = 0; i < s.length(); i++){
    12             if(needToFind[s.charAt(i)] == 0) continue;
    13             char c = s.charAt(i);
    14             found[c]++;
    15             if(found[c] <= needToFind[c])
    16                 count++;
    17             if(count == t.length()){
    18                 //move the begin pointer while the constrain meets
    19                 while(start < s.length() && ( needToFind[s.charAt(start)] == 0 || found[s.charAt(start)] > needToFind[s.charAt(start)])){
    20                     if(found[s.charAt(start)] > 0)
    21                         found[s.charAt(start)]--;
    22                     start++;
    23                 }
    24                 //update the min according to the current window
    25                 if(i - start + 1 < minWin){
    26                     minWin = i - start + 1;
    27                     res = s.substring(start,i + 1);
    28                 }
    29             }
    30         }
    31         return res;
    32     }
    33 }

    第二遍:

    minWin 初始化最好 > s.length(),否则当窗口大小== s.length时候,如果有重复最小窗口时候,代码可能就会稍微麻烦一点了。

    未通过case:"abc", "ac"

    这是一道很好的题目

    参考:

    http://www.cnblogs.com/jdflyfly/p/3815275.html

  • 相关阅读:
    Java并发
    JS的强制类型转换
    JS的原生函数
    JS的类型和值
    解决Oracle临时表空间占满的问题
    nginx location匹配规则
    java.util.ConcurrentModificationException 解决办法
    SQL优化三板斧:精简之道、驱动为王、集合为本
    一次非典型SQL优化:如何通过业务逻辑优化另辟蹊径?
    一次耐人寻味的SQL优化:除了SQL改写,还要考虑什么?
  • 原文地址:https://www.cnblogs.com/huntfor/p/3915288.html
Copyright © 2011-2022 走看看