您的位置:首页 > 其它

76 Minimum Window Substring

2015-10-26 20:57 239 查看
题目链接:https://leetcode.com/problems/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.


解题思路:

一开始总觉得是动态规划,想了半天没想出来。参考了大神的思路:/article/1378343.html

这道题是字符串处理的题目,和 30 Substring with Concatenation of All Words 思路非常类似,同样是建立一个字典,然后维护一个窗口。区别是在这道题目中,因为可以跳过没在字典里面的字符(也就是这个串不需要包含且仅仅包含字典里面的字符,有一些不在字典的仍然可以满足要求),所以遇到没在字典里面的字符可以继续移动窗口右端,而移动窗口左端的条件是当找到满足条件的串之后,一直移动窗口左端直到有字典里的字符不再在窗口里。在实现中就是维护一个 HashMap,一开始 key 包含字典中所有字符,value 就是该字符的数量,然后遇到字典中字符时就将对应字符的数量减一。算法的时间复杂度是 O(n) ,其中 n 是字符串的长度,因为每个字符再维护窗口的过程中不会被访问多于两次。空间复杂度则是 O(字典的大小),也就是代码中 T 的长度。

这个方法在 30 Substring with Concatenation of All Words 和 3 Longest Substring Without Repeating Characters 中都介绍过,属于一种类型的题目,只要掌握了思路便可以举一反三,都可以将这类问题降低到线性复杂度。

代码实现:

public class Solution {
public String minWindow(String s, String t) {
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return "";
HashMap<Character, Integer> map = new HashMap();
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 start = 0;
int count = 0;
int minLen = s.length() + 1;
int minStart = 0;
for(int end = 0; end < s.length(); end ++) {
if(map.containsKey(s.charAt(end))) {
map.put(s.charAt(end), map.get(s.charAt(end)) - 1);
if(map.get(s.charAt(end)) >= 0)
count ++;
while(count == t.length()) {
if(end - start + 1 < minLen) {
minLen = end - start + 1;
minStart = start;
}
if(map.containsKey(s.charAt(start))) {
map.put(s.charAt(start), map.get(s.charAt(start)) + 1);
if(map.get(s.charAt(start)) > 0)
count --;
}
start ++;
}
}
}
if(minLen > s.length())
return "";
return s.substring(minStart, minStart + minLen);
}
}


266 / 266 test cases passed.
Status: Accepted
Runtime: 48 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: