zoukankan      html  css  js  c++  java
  • 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 empty string "".
    If there are multiple such windows, you are guaranteed that there will always be only one unique
    minimum window in S.

    Solution: 1. Use two pointers: start and end.
    First, move 'end'. After finding all the needed characters, move 'start'.
    2. Use array as hashtable.

     1 class Solution {
     2 public:
     3     string minWindow(string S, string T) {
     4         int N = S.size(), M = T.size();
     5         if(N < M) return "";
     6         int need[256] = {0};
     7         int find[256] = {0};
     8         for(int i = 0; i < M; ++i)
     9             need[T[i]]++;
    10 
    11         int count = 0, resStart = -1, resEnd = N;
    12         for(int start = 0, end = 0; end < N; ++end) {
    13             if(need[S[end]] == 0)
    14                 continue;
    15             if(find[S[end]] < need[S[end]])
    16                 count++;
    17             find[S[end]]++;
    18             if(count != M) continue;
    19             // move 'start'
    20             for(; start < end; ++start) {
    21                 if (need[S[start]] == 0) continue;
    22                 if (find[S[start]] <= need[S[start]]) break;
    23                 find[S[start]]--;
    24             }
    25             // update result
    26             if(end - start < resEnd - resStart) {
    27                 resStart = start;
    28                 resEnd = end;
    29             }
    30         }
    31         return (resStart == -1) ? "" : S.substr(resStart, resEnd - resStart + 1);
    32     }
    33 };
  • 相关阅读:
    后台获取不规则排列RadioButton组的值
    通过使用ScriptManager.RegisterStartupScript,呈现后台多次使用alert方法
    通过获取DNS解析的未转义主机名,区分测试环境和正式环境代码
    Autolayout自动布局
    JSON和XML
    物理引擎UIDynamic
    呈现样式UIModalPresentation
    多线程 GCD
    FMDB数据库框架
    SQLite编码
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3676143.html
Copyright © 2011-2022 走看看