您的位置:首页 > 其它

LeetCode 76 Minimum Window Substring

2016-11-04 18:24 543 查看
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.

Runtime: 5
ms  beats 90.12% of java submissions.

public String minWindow(String s, String t) {
char[] ss = s.toCharArray(), tt = t.toCharArray();
int[] count = new int[128];
for (int i = 0; i < tt.length; i++) count[tt[i]]++;
int k = tt.length, minStart = 0, start = 0, minLen = Integer.MAX_VALUE;
for (int i = 0; i < ss.length; i++) {
if (count[ss[i]]-- > 0) k--;
while (k == 0) {
if (i - start + 1 < minLen) {
minLen = i - start + 1;
minStart = start;
}
count[ss[start]]++;
if (count[ss[start]] > 0) k++;
start++;
}
}
return minLen== Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
}


参考https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems/12
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode