Title:
Given a string S and a string T, find the minimum window in S which would 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 so covers all characters in T, return the emtpy string ""
.
If There is multiple such windows, you is guaranteed that there would always being only one unique minimum window in S.
Test Instructions:
Given a string s and a string T, find the smallest window in the string s, which can contain all the characters in T, and the time complexity requires O (n).
As an example:
S = "ADOBECODEBANC"
T = "ABC"
最下的窗口为"BANC"
.
Algorithm Analysis:
Double-pointer thinking, the tail pointer is constantly backward, when swept to a window containing all the characters of T, and then the little puss pointer, until it can no longer shrink.
The last record of all possible cases in which the window is the smallest
AC Code:
public class Solution {public string Minwindow (string S, String T) {hashmap<character, integer> H Asfound = new Hashmap<character, integer> (); Hashmap<character, integer> needtofind = new Hashmap<character, integer> (); for (int i = 0; i < t.length (); i++) {Hasfound.put (T.charat (i), 0); if (Needtofind.containskey (T.charat (i))) {Needtofind.put (T.charat (i), Needtofind.get (T.charat (i)) + 1); } else {needtofind.put (T.charat (i), 1); }} int begin = 0; int minwindowsize = S.length (); String retstring = ""; int count = 0; for (int end = 0; end < S.length (); end++) {Character End_c = S.charat (end); if (Needtofind.containskey (End_c)) {hasfound.put (End_c, Hasfound.get (End_c) + 1); if (Hasfound.get (End_c) <= needtofind.get (End_c)) {count++; } if (count = = T.length ()) {while (!needtofind.containskey (S.charat ( Begin))) | | (Hasfound.get (S.charat (BEGIN)) > Needtofind.get (S.charat (begin))) {if (Needtofind.containskey (S.charat (begin))) { Hasfound.put (S.charat (Begin), Hasfound.get (the S.charat (begin))-1); } begin++; } if ((End-begin + 1) <= minwindowsize) {minwindowsi Ze = end-begin + 1; RetString = s.substring (begin, End + 1); }}}} return retstring; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Minimum Window Substring