[LeetCode] 76. Minimum Window Substring
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.
Thought process:
Hash map + two pointers. Use a hash map to keep track of the occurrence of T's letters in S. The hash map maps a character in T to the remaining number of it to be matched. The value can also be negative, which means that there is one extra such character in the current window.
- Iterate through T. Populate map<letter, count>. This map represents the remaining characters in T to be matched.
- Iterate through S. Initialize variable count = t.length, window = empty string. Pointer i is the left end of the string. Pointer j is the right end of the string.
- If s[j] is in T, decrement map[s[j]]. Decrement count if map[s[j]] > 0.
- If count == 0, update minimum window.
- Increment i until map[s[i]] == 0. When I see an s[i] in T, increment map[s[i]].
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | class Solution { public String minWindow(String s, String t) { int count = t.length(); int i = 0; Map<Character, Integer> map = countCharacters(t); String window = ""; for (int j = 0; j < s.length(); j++) { char c1 = s.charAt(j); if (map.containsKey(c1)) { if (map.get(c1) > 0) { count--; } map.put(c1, map.get(c1) - 1); } if (count == 0) { char c2 = s.charAt(i); while (!map.containsKey(c2) || map.get(c2) < 0) { if (map.containsKey(c2)) { map.put(c2, map.get(c2) + 1); } i++; c2 = s.charAt(i); } if (window.length() == 0 || j - i + 1 < window.length()) { window = s.substring(i, j + 1); } } } return window; } private Map<Character, Integer> countCharacters(String s) { Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { int count = map.getOrDefault(c, 0); map.put(c, count + 1); } return map; } } |
Time complexity: O(n).
Comments
Post a Comment