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

reference: https://www.youtube.com/watch?v=63i802XLgOM

Solution:two pointers 滑动窗 + count_Map

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public String minWindow(String s, String t) {
        if(s == null || t == null || s.length() == 0 || t.length() == 0) return "";
        int match_count = 0;
        String result = "";
        
        int[] s_arr = new int[256];
        int[] t_arr = new int[256];
        for(char c: t.toCharArray()) {
            t_arr[c]++;
        }
        
        int left = findNextIndex(s, 0, t_arr);
        if(left == s.length()) return ""; // no char in S matches t
        int right = left;
        
        while(right < s.length()) {
            int right_char = s.charAt(right);
            if(s_arr[right_char] < t_arr[right_char]) {
                match_count++;
            }
            s_arr[right_char]++;
            
            while(left < s.length() && match_count == t.length()) {
                if(result.isEmpty() || result.length() > right - left + 1) {
                    result = s.substring(left, right + 1);
                }
                int left_char = s.charAt(left);
                if(s_arr[left_char] <= t_arr[left_char]) {
                    match_count--;
                }
                s_arr[left_char]--;
                left = findNextIndex(s, left + 1, t_arr);
            }
            right = findNextIndex(s, right + 1, t_arr);
        }
        return result;
        
    }
    
    private int findNextIndex(String s, int start, int[] t_arr) {
        while(start < s.length()) {
            char c = s.charAt(start);
            if(t_arr[c] != 0) return start;
            start++;
        }
        return start;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容