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.
Public classSolution { Publicstring Minwindow (string s, String t) {//The idea://use two arrays, with the letters subscript, a record of the total number of letters in T, a record of the number of times the letter has appeared in the current search//Handling Situation://1. When traversing the S-string, if the character appears in T, the number of times that has occurred must be accumulated .//2. Maintain a variable count, record how many valid substrings are currently present, and repeat the count of illegal characters multiple times ,//if the legal character equals the length of the substring, then a window is found. //3. Once found, you need to reposition the start intneedtofind[]=New int[256];//saves the number of characters that need to be found in T, which is no longer changed once the array is initialized inthasfound[]=New int[256];//saves the number of characters that have been found in S, and the array changes dynamically intminwindow=Integer.max_value; String Res=""; for(intI=0;i<t.length (); i++) {//initializes needtofind to the number of characters that need to be searched,Needtofind[t.charat (i)]++; } intStart=0; intEnd=0; intCount=0; for(; End<s.length (); end++) {//use end to traverse s string if(Needtofind[s.charat (end)]==0)Continue;//represents a character that can be ignored, that is, all characters except T CharTemp=s.charat (end);//find a character to look forHasfound[s.charat (end)]++; if(Needtofind[s.charat (end)]>=hasfound[s.charat (end)]) count++;//If the found is more than needed, there is no need to continue adding count if(Count==t.length ()) {//The window contains at least the T while(Needtofind[s.charat (start)]==0| | Needtofind[s.charat (start)]<Hasfound[s.charat (start)]) { //compress the window and move the start pointer backward, in which case the start pointer refers to the ignorable character if(Needtofind[s.charat (start)]<Hasfound[s.charat (start)]) { //another case is that the number of characters already found exceeds the number to be searched, so you can discard the extra partsHasfound[s.charat (start)]--;//discard the superfluous parts} start++;//Compress window } intWindow=end-start+1; if(Window<minwindow) {//Save Minimum windowRes=s.substring (start,end+1); Minwindow=window; } } } returnRes; }}
[Leedcode] Minimum Window Substring