题目描述:
给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
输出: true
示例 2:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
输出: false
思路:
动态规划
dp[i][j]表示s1的前 i 个字符,s2的前 j 个字符,能否组成s3的i+j 个字符
状态转移方程:
dp[i-1][j] and s1[i-1]==s3[i-1+j]) or (dp[i][j-1] and s2[j-1]==s3[j-1+i]
代码如下:
C++:
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n=s1.size();
int m=s2.size();
if(n+m!=s3.size()) return false;
vector<vector<bool>>dp(n+1,vector<bool>(m+1,false));
for(int i=0;i<=n;i++){
for(int j=0;j<=m;j++){
if(i==0&&j==0) dp[i][j]=true;
else if(i==0) dp[i][j]=dp[i][j-1]&&(s2[j-1]==s3[j-1]);
else if(j==0) dp[i][j]=dp[i-1][j]&&(s1[i-1]==s3[i-1]);
else dp[i][j]=(dp[i-1][j]&&s1[i-1]==s3[i-1+j])||(dp[i][j-1]&&s2[j-1]==s3[j-1+i]);
}
}
return dp[n][m];
}
};
Python:
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n=len(s1)
m=len(s2)
if n+m!=len(s3): return False
dp=[[False]*(m+1) for i in range(n+1)]
for i in range(n+1):
for j in range(m+1):
if i==0 and j==0:dp[i][j]=True
elif i==0:dp[i][j]=dp[i][j-1] and s2[j-1]==s3[j-1]
elif j==0:dp[i][j]=dp[i-1][j] and s1[i-1]==s3[i-1]
else:dp[i][j]=(dp[i-1][j] and s1[i-1]==s3[i-1+j]) or (dp[i][j-1] and s2[j-1]==s3[j-1+i])
return dp[-1][-1]