LC 727. Minimum Window Subsequence 【lock,hard】
阿新 • • 發佈:2018-12-22
Given strings S
and T
, find the minimum (contiguous) substring W
of S
, so that T
is a subsequenceof 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]
.
Runtime: 44 ms, faster than 73.35% of C++ online submissions for Minimum Window Subsequence.
網上的DP解法。dp定義是能夠匹配T[0,i]的最大的S的index.
舉個例子,S = babad, T = bad,
i = 0時,只有當j=0,兩個相等,所以此時dp = [0, -1, -1]
然後,dp = [0,1,-1],然後, dp = [2, 1, -1], -> dp[2,2,-1] -> dp[2,2,2]
因為時從後往前更新,只有當T的每一個字元都匹配了才能把最開頭的index傳遞到最後。中間即使有些匹配到,如果沒有全部匹配也傳遞不了。
比如 S = babd, T = bad,
dp = [-1,-1,-1] -> dp[0,-1,-1] -> dp[0,1,-1] -> dp[2,1,-1] -> dp[2,1,1] 結果還是1.
class Solution {
public:
string minWindow(string S, string T) {
vector<int> dp(T.length(), -1);
string ans = "";
for (int i = 0; i < S.length(); i++) {
for (int j = T.length() - 1; j >= 0; j--) {
if (S[i] == T[j]) {
if (j == 0) dp[j] = i;
else dp[j] = dp[j - 1];
}
}
int init = dp[T.length() - 1];
if (init != -1 && (ans == "" || i - init + 1 < ans.size())) {
ans = S.substr(init, i - init + 1);
}
}
return ans;
}
};
這題還有雙指標法,過段時間更新。