[LeetCode] 76. Minimum Window Substring, leetcode76.minimum
Question
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.
Analysis
For details, refer to [22 of the algorithm series] The minimum subwindow containing all T elements.
Code
/* ------------------------------------------ * Date: * Author: SJF0115 * Title: 76. minimum Window Substring * URL: Alert Result: AC * Source: LeetCode * Summary: Alert */# include <iostream> # include <algorithm> # include <climits> using namespace std; class Solution {public: string minWindow (string S, string T) {int slen = S. size (); Int tlen = T. size (); if (slen <= 0 | tlen <= 0) {return "" ;}// if int minWinStart = 0, minWinEnd = 0; int minWinLen = INT_MAX; // The total number of characters in T that have been stored so far int count = 0; // The total number of characters in T int needFind [256] = {0 }; for (int I = 0; I <tlen; ++ I) {++ needFind [T [I];} // for // store the total number of different characters encountered so far int hasFound [256] = {0}; int val; for (int start = 0, end = 0; end <slen; ++ end) {val = S [end]; // skip the character if (needFind [Val] = 0) {continue;} // if ++ hasFound [val]; if (hasFound [val] <= needFind [val]) {++ count ;} // if // find a valid window if (count = tlen) {int startVal = S [start]; while (needFind [startVal] = 0 | hasFound [startVal]> needFind [startVal]) {if (hasFound [startVal]> needFind [startVal]) {-- hasFound [startVal];} // if ++ start; startVal = S [start];} // while // update the minimum window int curWinLen = end-start + 1; if (curWinLen <min WinLen) {minWinLen = curWinLen; minWinStart = start; minWinEnd = end;} // if} // for if (count! = Tlen) {return "";} // if return S. substr (minWinStart, minWinEnd-minWinStart + 1) ;}; int main () {Solution solution; string S ("acbbaca"); string T ("aba "); cout <solution. minWindow (S, T) <endl ;}
Running time
Similar questions:
[Classic Interview Questions] [sogou] Find the minimum string containing all the characters in a string