美文网首页
727. Minimum Window Subsequence

727. Minimum Window Subsequence

作者: Jeanz | 来源:发表于2018-01-12 11:59 被阅读0次

    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中的substring, T中的字符保持它们的order, 也在substring中出现。
    对substring的限制条件是:最短的,如果有几个长度相同的,取第一个。

    用dynamic programing来做,dp[i][j]表示T[0, j]是S[0,i]的subsequence, 所以我们的目标函数就是min(i-dp[i][n-1]) for all i < m

    class Solution {
        public String minWindow(String S, String T) {
            int m = T.length(), n = S.length();
            int[][] dp = new int[m + 1][n + 1];
            for (int j = 0; j <= n; j++) {
                dp[0][j] = j + 1;
            }
            for (int i = 1; i <= m; i++) {
                for (int j = 1; j <= n; j++) {
                    if (T.charAt(i - 1) == S.charAt(j - 1)) {
                        dp[i][j] = dp[i - 1][j - 1];
                    } else {
                        dp[i][j] = dp[i][j - 1];
                }
            }
            }
    
            int start = 0, len = n + 1;
            for (int j = 1; j <= n; j++) {
                if (dp[m][j] != 0) {
                    if (j - dp[m][j] + 1 < len) {
                        start = dp[m][j] - 1;
                        len = j - dp[m][j] + 1;
                    }
                }
            }
            return len == n + 1 ? "" : S.substring(start, start + len);
        }
    }
    

    相关文章

      网友评论

          本文标题:727. Minimum Window Subsequence

          本文链接:https://www.haomeiwen.com/subject/muaxoxtx.html