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 = "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.

Solution:

  1. public class Solution {
  2. public String minWindow(String s, String t) {
  3. // step 1. create a hashmap for t
  4. char[] chsT = t.toCharArray();
  5. char[] chsS = s.toCharArray();
  6. Map<Character, Integer> map = new HashMap<Character, Integer>();
  7. for (int i = 0; i < chsT.length; i++) {
  8. char ch = chsT[i];
  9. int count = map.containsKey(ch) ? map.get(ch) : 0;
  10. map.put(ch, count + 1);
  11. }
  12. // step 2. use two pointers
  13. int i = 0, j = 0, count = 0;
  14. String res = "";
  15. while (j < s.length()) {
  16. char ch_j = chsS[j];
  17. if (map.containsKey(ch_j)) {
  18. // j find a character, update the count and the map
  19. if (map.get(ch_j) > 0) {
  20. count++;
  21. }
  22. map.put(ch_j, map.get(ch_j) - 1);
  23. while (count == t.length()) {
  24. // count the length of current substring
  25. if (res.equals("") || j - i + 1 < res.length()) {
  26. res = s.substring(i, j + 1);
  27. }
  28. char ch_i = chsS[i];
  29. if (map.containsKey(ch_i)) {
  30. // i find a character, update the count
  31. if (map.get(ch_i) >= 0) {
  32. count--;
  33. }
  34. map.put(ch_i, map.get(ch_i) + 1);
  35. }
  36. i++;
  37. }
  38. }
  39. j++;
  40. }
  41. return res;
  42. }
  43. }