您的位置:首页 > 其它

76. Minimum Window Substring

2018-02-02 18:56 393 查看
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.

class Solution {
public String minWindow(String s, String t) {
int start = 0, len = Integer.MAX_VALUE;
int[] times = new int[256];
int[] stimes = new int[256];
for(int i = 0; i < t.length(); i ++) {
times[t.charAt(i)] ++;
}
int cnt = 0;
int begin = -1, end = 0;
for(int i = 0; i < s.length(); i ++) {
char ch = s.charAt(i);
stimes[ch] ++;
if(stimes[ch] <= times[ch])
cnt ++;
if(cnt == t.length()) {
while(start < s.length() && stimes[s.charAt(start)] > times[s.charAt(start)]) {
stimes[s.charAt(start)] --;
start ++;
}

if(i - start + 1 < len) {
begin = start;
end = i;
len = i - start + 1;
}
stimes[s.charAt(start)] --;
start ++;
cnt --;
}
}
return begin == -1 ? "" : s.substring(begin, end + 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: