leetcode - 76.Minimum Window Substring

    xiaoxiao2021-03-25  66

    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:

    public String minWindow(String s, String t) { int[] map = new int[128]; for (char c : t.toCharArray()) { map[c]++; } int begin = 0; int end = 0; int counter = t.length(); int len = Integer.MAX_VALUE; int head = 0; while (end < s.length()) { if (map[s.charAt(end++)]-- > 0) counter--; while (counter == 0) { if (end - begin < len) len = end - (head = begin); if (map[s.charAt(begin++)]++ == 0) counter++; } } return len == Integer.MAX_VALUE ? "" : s.substring(head, head + len); }
    转载请注明原文地址: https://ju.6miu.com/read-40442.html

    最新回复(0)