76. Minimum Window Substring

来源:互联网 发布:大数据平台数据传输 编辑:程序博客网 时间:2024/06/01 17:25

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.

求包含字符串t的最小窗口。本题采用滑窗法求解,DP求解。

需注意,给定的字符串t中,可以包含重复的字符。程序如下所示:

class Solution {    public String minWindow(String s, String t) {        String ret = "";        Map<Character, Integer> map = new HashMap<>();        int count = t.length(), left = 0;        for (int i = 0; i < t.length(); ++ i){            if (map.containsKey(t.charAt(i))){                map.put(t.charAt(i), map.get(t.charAt(i)) + 1);            }            else {                map.put(t.charAt(i), 1);            }        }        int len = s.length(), minLen = Integer.MAX_VALUE;        int index = 0;        for (int i = 0; i < len; ++ i){            if (map.containsKey(s.charAt(i))){                map.put(s.charAt(i), map.get(s.charAt(i)) - 1);                if (map.get(s.charAt(i)) >= 0){                    count --;                }            }            while (count == 0){                if (minLen > i - left + 1){                    minLen = i - left + 1;                    index = left;                }                if (map.containsKey(s.charAt(left))){                    map.put(s.charAt(left), map.get(s.charAt(left)) + 1);                    if (map.get(s.charAt(left)) > 0){                        count ++;                    }                }                left ++;            }        }        if (minLen == Integer.MAX_VALUE){            return "";        }        return s.substring(index, index + minLen);    }}



原创粉丝点击