【leetcode】97. Interleaving String
题目如下:
解题思路:本题可以采用动态规划的方法。记dp[i][j]表示用s1的前i个字符和s2的前j个字符能否组成s3的前(i+j)个字符,如果dp[i-1][j]是True的话,只要s1[i] == s3[i-1+j],那么dp[i][j]就为True;同理,如果dp[i][j-1]是True,只要满足s2[j] == s3[i-1+j],那么dp[i][j]也为True。
代码如下:
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ if len(s1) + len(s2) == 0: return len(s3) == 0 elif len(s1) == 0: return s2 == s3 elif len(s2) == 0: return s1 == s3 elif len(s1) + len(s2) != len(s3): return False dp = [ [0]* (len(s2) + 1) for i in range(len(s1)+1) ] if s1[0] == s3[0]: dp[1][0] = 1 if s2[0] == s3[0]: dp[0][1] = 1 for i in range(len(dp)): for j in range(len(dp[i])): if i > 0 and j > 0 and dp[i-1][j] == 0 and dp[i][j-1] == 0: dp[i][j] = 0 elif i > 0 and dp[i-1][j] == 1 and s1[i-1] == s3[i-1+j]: dp[i][j] = 1 elif j > 0 and dp[i][j-1] == 1 and s2[j-1] == s3[i+j-1]: dp[i][j] = 1 #print dp return dp[-1][-1] == 1