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 =
T =
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 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.
Solution:
Method 1:
1. Use two pointers start and end to keep track of the minimum window that satisfy the condition.
2. Move end to find a valid window.
3. If we find a valid window, move start to find a smaller window.
Code:
public class Solution { public String minWindow(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.put(c, 0); } for (char c : t.toCharArray()) { if (!map.containsKey(c)) { map.put(c, 1); } else { map.put(c, map.get(c) + 1); } } int start = 0; int end = 0; int minStart = 0; int minLen = Integer.MAX_VALUE; int count = t.length(); while (end < s.length()) { char c1 = s.charAt(end); if (map.get(c1) > 0) { count--; } map.put(c1, map.get(c1) - 1); end++; while (count == 0) { if (end - start < minLen) { minLen = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if (map.get(c2) > 0) { count++; } start++; } } return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen); } }
Method 2:
Code:
public class Solution { public String minWindow(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : t.toCharArray()) { if (!map.containsKey(c)) { map.put(c, 1); } else { map.put(c, map.get(c) + 1); } } int len = Integer.MAX_VALUE; int head = 0; int start = 0; int end = 0; int count = map.size(); while (end < s.length()) { char c = s.charAt(end); if (map.containsKey(c)) { map.put(c, map.get(c) - 1); if (map.get(c) == 0) { count--; } } end++; while (count == 0) { if (end - start < len) { len = end - start; head = start; } char ch = s.charAt(start); if (map.containsKey(ch)) { map.put(ch, map.get(ch) + 1); if (map.get(ch) > 0) { count++; } } start++; } } if (len == Integer.MAX_VALUE) { return ""; } return s.substring(head, head + len); } }