您的位置:首页 > 其它

76. Minimum Window Substring

2017-01-08 09:39 260 查看
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.
参考模板Here is a 10-line template that can solve most 'substring' problems,基本可以解决所有的substring的问题。模板如下:
int findSubstring(string s){
vector<int> map(128,0);
int counter; // check whether the substring is valid
int begin=0, end=0; //two pointers, one point to tail and one  head
int d; //the length of substring

for() { /* initialize the hash map here */ }

while(end<s.size()){

if(map[s[end++]]-- ?){  /* modify counter here */ }

while(/* counter condition */){

/* update d here if finding minimum*/

//increase begin to make it invalid/valid again

if(map[s[begin++]]++ ?){ /*modify counter here*/ }
}

/* update d here if finding maximum*/
}
return d;
}
附上套模板的代码:

public class Solution {
public String minWindow(String s, String t) {
int[] map = new int[256];
for (char ch:t.toCharArray()) {
map[ch] ++;
}
int count = t.length(), begin = 0, end = 0, min = Integer.MAX_VALUE, head = 0;
while (end < s.length()) {
// change all characters not belong to string t to -1
if (map[s.charAt(end++)]-- > 0) count --;
while (count == 0) {
if (end - begin < min) {
min = end - begin;
head = begin;
}
if (map[s.charAt(begin++)]++ == 0) {
count ++;
}
}
}
if (min == Integer.MAX_VALUE) {
return "";
}
return s.substring(head, head + min);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: