给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。
比如 s1 = "aabcc" s2 = "dbbca"
- 当 s3 = "aadbbcbcac",返回 true.
- 当 s3 = "aadbbbaccc", 返回 false.
这是一道匹配的问题,我们用一个二维数组来存储s1和s2分别在s3中匹配的程度:
如:
match[i][j]表示s1字符串匹配到第i个字符,s2匹配到第j个字符
还有剩下的小问题就是一些索引的范围问题了,一定要注意每个字符串中索引的取值范围
贴代码:
class Solution:
"""
@param s1: A string
@param s2: A string
@param s3: A string
@return: Determine whether s3 is formed by interleaving of s1 and s2
"""
def isInterleave(self, s1, s2, s3):
# write your code here
l1 = len(s1)
l2 = len(s2)
l3 = len(s3)
match = [[False for i in range(l2+1)] for j in range(l1+1)]
match[0][0] = True
if l1+l2 != l3:
return False
for i in range(1,l1+1):
if s1[i-1]==s3[i-1]:
match[i][0] = True
for i in range(1, l2+1):
if s2[i-1] == s3[i-1]:
match[0][i] = True
for i in range(1,l1+1):
for j in range(1,l2+1):
k = i+j
if s1[i-1]==s3[k-1]:
match[i][j] = match[i][j] or match[i-1][j]
if s2[j-1]==s3[k-1]:
match[i][j]=match[i][j] or match[i][j-1]
return match[l1][l2]