您的位置:首页 > 其它

LeetCode Minimum Window Substring

2016-02-21 13:40 344 查看
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.

题意:给出字符串s和t,求t在s中出现的最小窗口

思路:统计字符串t 的计数,在遍历字符串s时,计数减1,如果计数等于0,同时更新最小窗口的起始位置和长度。

代码如下:

class Solution
{
public String minWindow(String s, String t)
{
int[] c = new int[128];;
for (int i = 0; i < t.length(); i++)
{
c[t.charAt(i)]++;
}

int count = t.length();

int start = 0, end = 0, min_len = Integer.MAX_VALUE;
int min_start = 0;

while (end < s.length())
{
if (c[s.charAt(end)] > 0) count--;
c[s.charAt(end)]--;

while (0 == count)
{
if (end - start + 1 < min_len)
{
min_start = start;
min_len = end - start + 1;
}

c[s.charAt(start)]++;
if (c[s.charAt(start)] > 0) count++;
start++;
}
end++;
}

if (min_len != Integer.MAX_VALUE) return s.substring(min_start, min_start + min_len);

return "";
}
}

解法二:先统计字符串s的计数,在遍历t过程中,计数减1。最后判断剩下的是否包含有t

class Solution
{
public String minWindow(String s, String t)
{
int[] c = new int[256];

for (char ch : s.toCharArray()) ++c[ch];

for (char ch : t.toCharArray())
{
if (--c[ch] < 0) return "";
}

int start = 0, end = s.length() - 1;
while (--c[s.charAt(end)] >= 0) --end;
++c[s.charAt(end)];
while (--c[s.charAt(start)] >= 0) ++start;
++c[s.charAt(start)];

String result = s.substring(start, end + 1);
int min = end - start + 1;

while (++end < s.length())
{
++c[s.charAt(end)];
while (--c[s.charAt(start)] >= 0) ++start;
++c[s.charAt(start)];

if (end - start + 1 < min)
{
result = s.substring(start, end + 1);
min = end - start + 1;
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: