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中的substring, T中的字符保持它們的order, 也在substring中出現(xiàn)。
對(duì)substring的限制條件是:最短的,如果有幾個(gè)長(zhǎng)度相同的,取第一個(gè)。

用dynamic programing來做,dp[i][j]表示T[0, j]是S[0,i]的subsequence, 所以我們的目標(biāo)函數(shù)就是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);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,039評(píng)論 0 23
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,899評(píng)論 0 33
  • 文/歐洛辰_ 本想做一棵朽木 便有不被砍伐的痛苦 還是做一棵參天大樹吧 終有保護(hù)你的幸福
    歐洛辰_閱讀 349評(píng)論 3 3
  • Transport . water - ferry - boat - ship - submarine: svbm...
    享悅moonlight閱讀 379評(píng)論 0 0
  • 現(xiàn)在外面打著閃,我躲在宿舍里,聽著情歌,抱著我的被子。剛剛和失而復(fù)得的好友互道晚安,很享受。不知都以后會(huì)有什么,盡...
    不如緣到夢(mèng)里去閱讀 193評(píng)論 0 0

友情鏈接更多精彩內(nèi)容