LeetCode 76. Minimum Window Substring(java)

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,
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.

以下的代码解法是从直接看第i位的数，然后分情况讨论的原子操作想法出发，1. i不属于T，do nothing; 2. i属于T，2.1 已经存在结果，那么freq(s.charAt(i))++, move start until Tfreq(start) == Sfreq(start), 2.2 不存在结果，freq(s.charAt(i))++, 如果此时存在了，那么delete until Tfreq(start) == Sfreq(start).
public static String minWindow(String s, String t) {
//T-Table
int count = 0, start = 0, min = Integer.MAX_VALUE;
String res = "";
int[] mapT = new int[256];
for (int i = 0; i < t.length(); i++) {
mapT[t.charAt(i)]++;
}
//S-Table
int[] mapS = new int[256];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mapT[c] > 0) {
mapS[c]++;
if (count >= t.length()) {
//move start
start = moveStart(start, mapS, mapT, s);
} else {
if (mapT[c] >= mapS[c]) {
count++;
if (count >= t.length()) {
start = moveStart(start, mapS, mapT, s);
}
}
}
}
if (count >= t.length() && i - start + 1 < min) {
min = i - start + 1;
res = s.substring(start, i + 1);
}
}
return res;
}
public static int moveStart(int start, int[] mapS, int[] mapT, String s) {
while (mapT[s.charAt(start)] == 0 || mapS[s.charAt(start)] > mapT[s.charAt(start)]) {
if (mapT[s.charAt(start)] > 0) {
mapS[s.charAt(start)]--;
}
start++;
}
return start;
}


Java学习指南系列（Java快速入门）

2017年08月09日 15:30

[leetcode-76]Minimum Window Substring(java)

2015-08-05 20:28:08

LeetCode76——Minimum Window Substring

2015-11-17 20:59:57

LeetCode --- 76. Minimum Window Substring

2015-03-23 21:26:09

LeetCode(76)Minimum Window Substring

2015-03-22 08:05:39

[Leetcode]76. Minimum Window Substring @python

2016-01-21 21:52:24

[LeetCode][Java] Minimum Window Substring

2015-07-18 10:34:09

LeetCode 76. Minimum Window Substring（最小窗口子串）

2016-05-22 05:19:30

Minimum Window Substring -- LeetCode

2014-03-03 04:23:50

leetCode 76.Minimum Window Substring(最小窗口子串) 解题思路和方法

2015-07-19 16:43:06

不良信息举报

LeetCode 76. Minimum Window Substring(java)