文章 224
评论 6
浏览 200766
Dynamic Programming - 97. Interleaving String

Dynamic Programming - 97. Interleaving String

97. Interleaving String

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

思路:

题目意思是指如果用s1和s2可以拼出s3就返回true,但注意拼接的时候是存在顺序的,就是用来拼接s1和s2的字符在s3中顺序需要和原来一样。考虑最后一步是s3的最后一个字母该来自于谁,之前的拼接出来的结果是否合法,就等价于一个拼接合法字符串加上s1或者s2最后一个字符等于最终结果,这就把问题退化为求上一个合法字符串拼接的问题,很明显,可以用动态规划来做.
如图:

(  )s1 0 d b b c a
s2
0      T F F F F F
a      T F F F F F
a      T T T T T F
b      F T T F T F
c      F F T T T T
c      F F F T F T

状态转移方程就是dp[i][j] = (dp[i-1][j] && s2.charAt(i-1) == s3.charAt(i+j-1) || dp[i][j-1] && s1.charAt(j-1) == s3.charAt(i+j-1), 其中dp[i][j]代表当前位置是否可以用s1和s2和上一个字符串拼接出来。初始条件和边界条件是s1为空s2为空,那么s3一定为空,所以dp[0][0] = true,而当s1为空s2应该和s3一一对应,所以每比较一位就看上一个状态合不合法,就能决定当前是否合法。

代码:

go:

func isInterleave(s1 string, s2 string, s3 string) bool {
    if len(s1) + len(s2) != len(s3) {
        return false
    }
    
    m, n := len(s2), len(s1) 
    dp := make([][]bool, m+1)
    for i := 0; i < m + 1; i++ {
        dp[i] = make([]bool, n+1)
    }

    for i := 0; i < m+1; i++ {
        for j := 0; j < n+1; j++ {
            if i == 0 && j != 0 {
                dp[i][j] = dp[i][j-1] && (s1[j-1] == s3[j-1])
            } else if i != 0 && j == 0 {
                dp[i][j] = dp[i-1][j] && (s2[i-1] == s3[i-1])
            } else if i == 0 && j == 0 {
                dp[i][j] = true
            } else {
                dp[i][j] = ((dp[i-1][j] && s2[i-1] == s3[i+j-1]) || (dp[i][j-1] && s1[j-1] == s3[i+j-1]))
            }
        } 
        
    }

    return dp[m][n]
}

标题:Dynamic Programming - 97. Interleaving String
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/07/1565192569029.html

Nothing just happens, it's all part of a plan.

取消