Description
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
分析
题目的意思是:s3能否通过s1和s2交错排列得到。
s3是由s1和s2交织生成的,意味着s3由s1和s2组成,在s3中s1和s2字符的顺序是不能变化的,和子序列题型类似,这种题我们一般是用动态规划来解。
- 设dp[i][j]表示s3的前i+j个字符可以由s1的前i个字符和s2的前j个字符交织而成。
- 状态转移方程:有两种情况
2.1 第一个状态转移方程:
dp[i][j]= (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]
dp[i-1][j]表示若s3的前i+j-1个字符能够由s1前i-1个字符和s2的前j个字符交织而成,那么只需要s1的第i个字符与s3的第i+j个字符相等,那么dp[i][j]=true;
2.2 第二个状态转移方程:
dp[i][j]= dp[i][j-1] && s2[j - 1] == s3[i + j - 1]
dp[i-1][j]表示若s3的前i+j-1个字符能够由s1前i个字符和s2的前j-1个字符交织而成,那么只需要s2的第j个字符与s3的第i+j个字符相等,那么dp[i][j]=true;
C++实现
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n1=s1.length();
int n2=s2.length();
int n3=s3.length();
if(n1+n2!=n3){
return false;
}
vector<vector<bool>> dp(n1+1,vector<bool>(n2+1,false));
for(int i=0;i<=n1;i++){
for(int j=0;j<=n2;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[i+j-1];
}else if(j==0){
dp[i][j]=dp[i-1][j]&&s1[i-1]==s3[i+j-1];
}else{
dp[i][j]=(dp[i-1][j]&&s1[i-1]==s3[i+j-1])||(dp[i][j-1]&&s2[j-1]==s3[i+j-1]);
}
}
}
return dp[n1][n2];
}
};
Python实现
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
# dp[i][j]=dp[i-1][j] if s1[i-1]==s3[i+j-1]
# dp[i][j]=dp[i][j-1] if s2[j-1]==s3[i+j-1]
m = len(s1)
n = len(s2)
dp = [[False]*(n+1) for _ in range(m+1)]
if m+n!=len(s3):
return False
for i in range(m+1):
for j in range(n+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[i+j-1]
elif j==0:
dp[i][j]=dp[i-1][j] and s1[i-1]==s3[i+j-1]
else:
dp[i][j]= (dp[i][j-1] and s2[j-1]==s3[i+j-1]) or (dp[i-1][j] and s1[i-1]==s3[i+j-1])
return dp[m][n]
下面是另一个版本,做了模块化处理:
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m = len(s1)
n = len(s2)
if m+n!=len(s3):
return False
dp= [[False]*(n+1) for _ in range(m+1)]
dp[0][0]=True
for i in range(1,m+1):
dp[i][0]= dp[i-1][0] and s1[i-1]==s3[i-1]
for j in range(1,n+1):
dp[0][j]=dp[0][j-1] and s2[j-1]==s3[j-1]
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=dp[i-1][j] and s1[i-1]==s3[i+j-1]
dp[i][j]=dp[i][j] or (dp[i][j-1] and s2[j-1]==s3[i+j-1])
return dp[m][n]
参考文献
[编程题]interleaving-string
[LeetCode] Interleaving String 交织相错的字符串
97. Interleaving String