Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 =
s2 =
Given:
s1 =
"aabcc"
,s2 =
"dbbca"
,
When s3 =
When s3 =
"aadbbcbcac"
, return true.When s3 =
"aadbbbaccc"
, return false.Solution:
We use dynamic programming, with the matrix isInterleaved whose element(i,j) indicates if string s3[0,...,i+j-1] can be formed by interleaving s1[0,...,i-1] and s2[0,...,j-1].Then we can just calculate the element (i,j) by:
isInterleaved[i][j] = (isInterleaved[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1)) || (isInterleaved[i][j-1] && s2.charAt(j-1)==s3.charAt(i+j-1))
Instead of using $O(n*m)$ space to keep the whole matrix, we can just keep the previousRow and the actual row, reducing to $O(m)$ space
class Solution: # @return a boolean def isInterleave(self, s1, s2, s3): isInterleaved = [] if len(s3) != len(s1)+len(s2): return False for i in range(0,len(s1)+1): row = [] for j in range(0,len(s2)+1): if i == 0 and j==0: row.append(True) else: temp = False if j>0: temp = row[j-1] and s3[i+j-1] == s2[j-1] if i>0: temp = temp or (previousRow[j] and s3[i+j-1] == s1[i-1]) row.append(temp) previousRow = row return row[len(s2)]
No comments :
Post a Comment