版权声明:小明酱私有,私自转载要捶你小胸口哦~ https://blog.csdn.net/alicelmx/article/details/83303621
题目
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
基本思路
动态规划
DP[i][j]表示s1取前i位,s2取前j位,检查是否能组成s3的前i+j位。
举个列子:
从DP[0][1] 往下的箭头表示,s1目前取了前0位,s2目前取了1位,添加s1的第1位,检查它是否等于s3的第(i+j)位。
从DP[1][0] 往右的箭头表示,s1目前取了1位,s2目前取了0位,我们添加s2的第1位,检查它是否等于s3的第(i+j)位。
若要取True,必须同时满足2个条件:
- 新添加的字符,要等于s3里面对应的第(i+j)位。
- 该格子的前一个格子也要等于True。
此外,还有4个地方需要注意:
- 初始时,应将DP[0][0]设为True。
- 对于DP中的第0行(除了DP[0][0])中的每一个格子,它的前一步是其左边的格子。
- 对于DP中的第0列(除了DP[0][0])中的每一个格子,它的前一步是其上边的格子。
- 对于DP中的其他格子(即DP[i][j],i>0,j>0),它的前一步是其左边的或其上边的格子,在这个情况下,有2条路径可以到达DP[i][j],只要有一条路径走得通,DP[i][j]就设为True。
实现代码
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if (len(s1) + len(s2)) != len(s3):
return False
DP = [[False for i in range(len(s2)+1)] for j in range(len(s1)+1)]
DP[0][0] = True
for i in range(len(s1)+1):
for j in range(len(s2)+1):
if i>0 and DP[i-1][j] and s3[i+j-1] == s1[i-1]:
DP[i][j] = True
elif j>0 and DP[i][j-1] and s3[i+j-1] == s2[j-1]:
DP[i][j] = True
return DP[len(s1)][len(s2)]