727. Minimum Window Subsequence
题目链接
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string “”. If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Input:
S = "abcdebdde", T = "bde"
Output: "bcde"
Explanation:
"bcde" is the answer because it occurs before "bdde" which has the same length.
"deb" is not a smaller window because the elements of T in the window must occur in order.
Note:
All the strings in the input will only contain lowercase letters.
The length of S will be in the range [1, 20000].
The length of T will be in the range [1, 100].
题目大意
给定字符串S和T,在S中寻找最小子串W,使得T是W的子序列。
解题思路
状态
- dp[i][j] 表示S中前i个字符包含T中前j个字符的起始位置。
转移方程
- 如果S[i - 1]字符等于T[j - 1],那么起始位置可以参考dp[i - 1][j - 1]
- 如果不等,那么起始位置参考dp[i - 1][j]
复杂度
TC: O(n^2)
SC: O(n^2)
public String minWindow(String S, String T) {
int m = S.length(), n = T.length(), start = -1, minLen = Integer.MAX_VALUE;
int[][] dp = new int[m + 1][n + 1];
for (int[] d: dp) Arrays.fill(d, -1);
for (int i = 0; i <= m; ++i) dp[i][0] = i; //匹配空字符在S中的起始位置
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= Math.min(i, n); ++j) { //t需要匹配的长度总小于s
dp[i][j] = S.charAt(i - 1) == T.charAt(j - 1) ? dp[i - 1][j - 1] : dp[i - 1][j];
}
if (dp[i][n] != -1) {
int len = i - dp[i][n];
if (minLen > len) {
minLen = len;
start = dp[i][n];
}
}
}
//printMatrix(dp);
return (start != -1) ? S.substring(start, start + minLen) : "";
}
76. Minimum Window Substring
题目链接
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).
Example:
Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
题目大意
在S中找出包含T的全部字符的最小子串。
解题思路
滑动窗口
复杂度
TC: O(n)
SC: O(256)
public String minWindow(String s, String t) {
int minLen = Integer.MAX_VALUE;
int cnt = t.length();
int[] map = new int[256];
int start = -1;
for (int i = 0; i < t.length(); i++){
map[t.charAt(i)]++;
}
int left= 0;
int right = 0;
while(right < s.length()){
if(map[s.charAt(right)]-- > 0){
cnt--;
}
while(cnt == 0){
int curLen = right - left + 1;
if (curLen < minLen){
minLen = curLen;
start = left;
}
if (map[s.charAt(left++)]++ >= 0){
cnt++;
}
}
right++;
}
return start == -1? "":s.substring(start, start + minLen);
}