Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
Example
Example 1:
Input:
"aabcc"
"dbbca"
"aadbbcbcac"
Output:
true
Example 2:
Input:
""
""
"1"
Output:
false
Example 3:
Input:
"aabcc"
"dbbca"
"aadbbbaccc"
Output:
false
Challenge
O(n2) time or better
需要考虑回退的情况 因此用递归来做
i,j,k 分别记录 s1 s2 s3 下一个应该比较的元素
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
if len(s1) + len(s2) != len(s3):
return False
self.s1 = s1
self.s2 = s2
self.s3 = s3
return self.dfs()
def dfs(self, i=0, j=0, k=0):
if k == len(self.s3) and j == len(self.s2) and i ==len(self.s1):
return True
r1, r2 = None, None
if i < len(self.s1) and self.s3[k] == self.s1[i]:
r2 = self.dfs(i+1, j, k+1)
if j<len(self.s2) and self.s3[k] == self.s2[j]:
r1 = self.dfs(i, j+1, k+1)
if r1 is None and r2 is None:
return False
return r1 or r2