Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
Subscribe to see which companies asked this question
可以用递归做,每匹配s1或者s2中任意一个就递归下去。但是会超时。
因此考虑用动态规划做。
s1, s2只有两个字符串,因此可以展平为一个二维地图,判断是否能从左上角走到右下角。
当s1到达第i个元素,s2到达第j个元素:
地图上往右一步就是s2[j-1]匹配s3[i+j-1]。
地图上往下一步就是s1[i-1]匹配s3[i+j-1]。
示例:s1="aa",s2="ab",s3="aaba"。标1的为可行。最终返回右下角。
0 a b
0 1 1 0
a 1 1 1
a 1 0 1
class Solution(object):
def isInterleave(self, s1, s2, s3):
if s3 == '':
return True
if len(s1) + len(s2) != len(s3):
return False
if s1 == '' or s2 == '':
return s3 == s1 + s2
dp = []
for i in xrange(len(s2)+1):
dp += [0] * (len(s1)+1),
if s1[0] == s3[0] or s2[0] == s3[0]:
dp[0][0] = 1
for i in xrange(len(s1)):
if (s1[i] == s3[i]) and dp[0][i] == 1:
dp[0][i+1] = 1
for i in xrange(len(s2)):
if s2[i] == s3[i] and dp[i][0] == 1:
dp[i+1][0] = 1
for i in xrange(len(s2)):
for j in xrange(len(s1)):
#print i,j,s1[j],s2[i],s3[i+j+1]
if (dp[i+1][j] == 1 and s1[j] == s3[i+j+1]) or (dp[i][j+1] == 1 and s2[i] == s3[i+j+1]):
dp[i+1][j+1] = 1
return dp[-1][-1] == 1
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""