May 22, 2020 10:48 Technology
This is a LeetCode hard question solved by dynamic programming (2d).
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
class Solution(object):
def isInterleave(self, s1, s2, s3):
if len(s3) == len(s1) + len(s2):
table = [[False for i in range(len(s1)+1)] for j in range(len(s2)+1)]
table[0][0] = True
for j in range(1, len(s1)+1):
table[0][j] = table[0][j-1] and (s1[j-1] == s3[j-1])
for i in range(1, len(s2)+1):
table[i][0] = table[i-1][0] and (s2[i-1] == s3[i-1])
for j in range(1, len(s1)+1):
table[i][j] = (table[i-1][j] and (s2[i-1] == s3[i+j-1])) or \
(table[i][j-1] and (s1[j-1] == s3[i+j-1]))
return table[-1][-1]
else:
return False