[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming
Posted johnsonxiong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming相关的知识,希望对你有一定的参考价值。
Given s1, s2, s3, 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
这个题目利用dynamic programming,mem[l1 + 1][l2 + 1] #mem[i][j] means that whether the first i characters of s1 and the first j characters of s2 be able to make first i + j characters of s3.
mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1]) # when the last character of s3 matches the last of s1
or (mem[i][j - 1]) and s2[j - 1] == s3[i + j - 1]) # when the last character of s3 matches the last of s2
initial: mem[i][0] = s1[:i] == s3[:i]
mem[0][j] = s2[:j] == s3[:j]
code
class Solution: def interLeaveString(self, s1, s2, s3): l1, l2, l3 = len(s1), len(s2), len(s3) if l1 + l2 != l3: return False mem = [[False] * (l2 + 1) for _ in range(l1 + 1)] for i in range(l1 + 1): mem[i][0] = s1[:i] == s3[:i] for j in range(l2 + 1): mem[0][j] = s2[:j] == s3[:j] for i in range(1, 1 + l1): for j in range(1, 1 + l2): mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (mem[i][j - 1] and s2[j - 1] == s3[i + j - 1]) return mem[l1][l2]
以上是关于[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-97-Interleaving String]