October 13, 2019

76. Minimum Window Substring

76. Minimum Window Substring

Two pointers, sliding window + hashtable. Time = O(n).
Similar to 438. Find All Anagrams in a String

class Solution {
    public String minWindow(String s, String t) {
        if (t.length() > s.length()) {
            return "";
        }
        Map<Character, Integer> map = new HashMap<>();
        for (char c : t.toCharArray()) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        int counter = map.size();
        int i = 0;
        int j = 0;
        int head = 0;
        int length = Integer.MAX_VALUE;
        while (j < s.length()) {
            char jChar = s.charAt(j);
            if (map.containsKey(jChar)) {
                map.put(jChar, map.get(jChar) - 1);
                if (map.get(jChar) == 0) {
                    counter --;
                }
            }
            j++;
            
            while (counter == 0) {
                char iChar = s.charAt(i);
                if (map.containsKey(iChar)) {
                    map.put(iChar, map.get(iChar) + 1);
                    if (map.get(iChar) > 0) {
                        counter ++;
                    }
                }
                if (j - i < length) {
                    length = j - i;
                    head = i;
                }
                i ++;
            }
        }
        if (length == Integer.MAX_VALUE) {
            return "";
        }
        return s.substring(head, head + length);
    }
}

另一种写法:

class Solution {
    public String minWindow(String s, String t) {
        if (s == null || t == null || s.length() == 0 || t.length() == 0) {
            return "";
        }
        String res = "";
        int count = 0;
        int minLen = Integer.MAX_VALUE;
        int[] tArray = new int[256];
        for (char c : t.toCharArray()) {
            tArray[c] ++;
        }
        int[] sArray = new int[256];
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (tArray[c] == 0) {
                continue;
            }
            if (sArray[c] < tArray[c]) {
                count ++;
            }
            sArray[c]++;
            while (count == t.length()) {
                if (i - j + 1 < minLen) {
                    minLen = i - j + 1;
                    res = s.substring(j, i + 1);
                }
                c = s.charAt(j);
                if (tArray[c] != 0) {
                    if (sArray[c] <= tArray[c]) {
                        count --;
                    }
                    sArray[c] --;
                }
                j++;
            }
        }
        return res;
    }
}
comments powered by Disqus