Leetcode 97. Interleaving String
阿新 • • 發佈:2018-12-10
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
Answer:
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ l1=len(s1) l2=len(s2) l3=len(s3) if l1+l2!=l3: return False dp=[[False]*(l1+2) for _ in range(l2+2)] dp[0][0]=True for i in range(1,l1+1): if s3[i-1]==s1[i-1]: dp[0][i]=dp[0][i-1] else: break for i in range(1,l2+1): if s3[i-1]==s2[i-1]: dp[i][0]=dp[i-1][0] else: break for i in range(1,l2+1): for j in range(1,l1+1): if s3[i+j-1]==s1[j-1]: dp[i][j]=dp[i][j] or dp[i][j-1] if s3[i+j-1]==s2[i-1]: dp[i][j]=dp[i][j] or dp[i-1][j] return dp[l2][l1]