题目来源:
https://leetcode.com/problems/interleaving-string/
题意分析:
给定字符串s1,s2,s3,判断s3是否由s1和s2穿插组成。如“abc”由“ac”,“b”组成,而“cba”不是。
题目思路:
这是一个动态规划问题。令ans[i][j]为s1[:i]和s2[:j]匹配是否成功。那么动态方程是if s1[i - 1] == s3[i + j - 1] 那么ans[i][j] = ans[i][j] or ans[i - 1][j];if s2[j - 1] == s3[i + j - 1] 那么ans[i][j] = ans[i][j] or ans[i][j - 1]。
代码(python):
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ i,j,k = 0,0,0 m,n,t = len(s1),len(s2),len(s3) if m + n != t: return False ans = [[False for i in range(n+1)] for j in range(m+1)] ans[0][0] = True for i in range(1,m+1): if s1[i - 1] == s3[i - 1]: ans[i][0] = True else: break for i in range(1,n + 1): if s2[i - 1] == s3[i -1]: ans[0][i] = True else: break for i in range(1,m + 1): for j in range(1,n + 1): if s1[i - 1] == s3[i + j - 1]: ans[i][j] = ans[i][j] or ans[i - 1][j] if s2[j - 1] == s3[i + j - 1]: ans[i][j] = ans[i][j] or ans[i][j - 1] return ans[m][n]