76. 最小覆盖子串
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
注意:
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
    public String minWindow(String s, String t) {
        int[] count = new int[256];
        String ans = "";
        int minLength = Integer.MAX_VALUE;
        for (int i = 0; i < t.length(); ++i) {
            count[t.charAt(i)]++;
        }
        int left = 0, right = 0, need = t.length();
        while (right < s.length()) {
            if (count[s.charAt(right++)]-- > 0) {
                --need;
                if (need == 0) {
                    while (count[s.charAt(left)] < 0) {
                        count[s.charAt(left++)]++;
                    }
                    if (right - left < minLength) {
                        minLength = right - left;
                        ans = s.substring(left, right);
                    }
                    count[s.charAt(left++)]++;
                    need++;
                }
            }
        }
        return ans;
    }
}
class Solution {
    public String minWindow(String s, String t) {
        if (s == null || s.length() == 0 || t == null || t.length() == 0) {
            return "";
        }
        int length = s.length();
        String ans = "";
        int left = 0, right = 0;
        int[] count = new int[256];
        int types = 0;
        for (int i = 0; i < t.length(); i++) {
            count[t.charAt(i)]++;
            if (count[t.charAt(i)] == 1) {
                types++;
            }
        }
        while (right < s.length()) {
            count[s.charAt(right)]--;
            if (count[s.charAt(right)] == 0) {
                types--;
            }
            if (types == 0) {
                while (left <= right && types == 0) {
                    if (++count[s.charAt(left++)] == 1) {
                        types++;
                    }
                }
                if (right - left + 2 <= length) {
                    length = right - left + 2;
                    ans = s.substring(left - 1, right + 1);
                }
            }
            right++;
        }
        return ans;
    }
}
    心之所向,素履以往 生如逆旅,一苇以航

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号