Tuesday, January 17, 2017

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.

/*
Set an array to record the number of each character in string t. Use two pointers to iterate string s, when the substring in string s contains string t, if the length of the substring is smaller than the previous recorded length, update the minimum window substring. Then move forward the left pointer and continue to check if the new substring contains string t.

time:O(n), space:O(1)
*/
public class Solution {
    public String minWindow(String s, String t) {
        if (s == null || s.length() == 0 || t == null) {
            return "";
        }
        int[] map = new int[256];
        for (char ch : t.toCharArray()) {
            map[ch]++; 
        }
        int i = 0;
        int j = 0;
        int count = t.length();
        int length = Integer.MAX_VALUE;
        String res = "";
        for (i = 0; i < s.length() - t.length() + 1; i++) {
            while (j < s.length() && count > 0) {
                if (map[s.charAt(j)]-- > 0) {
                    count--;
                }
                j++;
            }
            if (count == 0 && j - i < length) {
                length = j - i;
                res = s.substring(i, j);
            }
            if (map[s.charAt(i)]++ == 0) {
                count++;
            }
        }
        return res;
    }
}

No comments:

Post a Comment