LeetCode, leetcodeoj
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 empty string""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Train of Thought: for example
S = "aabcdafac" T = "ac"
Save the two pointers and point them to the start and end positions of the currently found string. We first find aabc, which is the first string containing the ac. Okay, this length is 4, start = 0, end = 3. At this time, keep the end unchanged and move start. It is found that start = 1 and end = 3 can be shorter. Then start cannot be moved.
Next, let's move the end and find that moving to end = 4, Not a or c, then move it again, move to end = 5, and find that it is a, then start or 1, let's move start, it can be moved to start = 3 all the time.
Next, move the end, and so on.
When we walk through the code, we will find that this idea is still linear.
package string;import java.util.HashMap;import java.util.Map;public class MinimumWindowSubstring { public String minWindow(String s, String t) { int m = s.length(); int n = t.length(); Map<Character, Integer> found = new HashMap<Character, Integer>(); Map<Character, Integer> base = new HashMap<Character, Integer>(); for (int i = 0; i < n; ++i) { char c = t.charAt(i); if (base.containsKey(c)) { base.put(c, base.get(c) + 1); } else { base.put(c, 1); found.put(c, 0); } } int count = 0; int ss = -1; int ee = m; for (int end = 0, start = 0; end < m; ++end) { char c = s.charAt(end); if (base.containsKey(c)) { found.put(c, found.get(c) + 1); if (found.get(c) <= base.get(c)) ++count; if (count == n) { char startChar = s.charAt(start); while (!base.containsKey(startChar) || found.get(startChar) > base.get(startChar)) { if (base.containsKey(startChar)) found.put(startChar, found.get(startChar) - 1); startChar = s.charAt(++start); } if (end - start < ee - ss) { ee = end; ss = start; } } } } return ss == -1 ? "" : s.substring(ss, ee + 1); } public static void main(String[] args) { // TODO Auto-generated method stub String S = "ADOBECODEBANC"; String T = "ABC"; MinimumWindowSubstring m = new MinimumWindowSubstring(); System.out.println(m.minWindow(S, T)); }}