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.
Use a hashmap to store the elements in T, and record the number of each element, then use two pointers, the tail pointer backwards until the substring contains all T, and then the head pointer backwards until the substring cannot contain all t, and the length of the substring is recorded
Reference: Leetcode Dai Fangqin
public class Solution {public String Minwindow (string S, String T) {if (s.length () = = 0) return ""; map<character,integer> map = new hashmap<> (); for (int i=0;i<t.length (); i++) {Integer n = map.get (T.charat (i)); Map.put (T.charat (i), n==null?1:n+1); } map<character,integer> lin = new hashmap<> (); int minstart = S.length (); int width = s.length () +1;; int start = 0; int app = 0; for (int end = 0;end<s.length (); end++) {char c = s.charat (end); Boolean in = false; if (Map.containskey (c)) {Integer num = Lin.get (c); Lin.put (c, num==null?1:num+1); if (Lin.get (c) <=map.get (c)) {app++; }} while (App==t.length ()) {in = true; char cc = S.charat (start); if (Lin.containskey (cc)) {lin.put (CC, Lin.get (cc)-1); if (Lin.get (CC) <map.get (cc)) {app--; }} start++; } if (in&&end-start+2<width) {minstart = start-1; width = end-start+2; }} if (width= = S.length () +1) return ""; Return s.substring (minstart,minstart+width); }}
[Leetcode] Minimum Window Substring