1. 题目
给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true示例 2:
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/interleaving-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 交错组成:s1、s2 每个字符都要先从左边开始拿,次序随意,看能否组成 s3
dp[i][j]
表示 s1 取了 i 个,s2 取了 j 个,可以匹配 s3 前面的- 那么假设
dp[i][j]
已求出可以匹配,那么下一个状态就是取 s1 的第 i+1个(if s1[i] == s3[i+j]
),或者取 s2 的第 j+1 个(if s2[j] == s3[i+j]
)
class Solution { //C++
public:bool isInterleave(string s1, string s2, string s3) {if(s1.size()+s2.size() != s3.size())return false;int m = s1.size(), n = s2.size(), i, j, k;vector<vector<int>> dp(m+1,vector<int>(n+1,0));// dp[i][j] 表示 s1取了i个,s2取了 j 个,可以匹配s3前面的dp[0][0] = 1;for(i = 0; i < m; i++) if(s1[i] == s3[i])dp[i+1][0] = 1;elsebreak;for(i = 0; i < n; i++)if(s2[i] == s3[i])dp[0][i+1] = 1;elsebreak;for(i = 1; i <= m; ++i)for(j = 1; j <= n; j++){ //要求 i,j 状态,该状态下s3是第i+j个字符k = i+j;if(s1[i-1] == s3[k-1])//s1的第i个字符匹配dp[i][j] |= dp[i-1][j];if(s2[j-1] == s3[k-1])//s2的第j个字符匹配dp[i][j] |= dp[i][j-1];}return dp[m][n];}
};
4 ms 6.9 MB
- python3 解答
class Solution:def isInterleave(self, s1: str, s2: str, s3: str) -> bool:m, n = len(s1), len(s2)if m+n != len(s3):return False;dp = [[0]*(n+1) for _ in range(m+1)]dp[0][0] = 1for i in range(m):if s1[i] == s3[i]:dp[i+1][0] = 1else:breakfor i in range(n):if s2[i] == s3[i]:dp[0][i+1] = 1else:breakfor i in range(1,m+1):for j in range(1,n+1):k = i+jif s1[i-1] == s3[k-1]:dp[i][j] |= dp[i-1][j]if s2[j-1] == s3[k-1]:dp[i][j] |= dp[i][j-1]return True if dp[m][n] else False
64 ms 13.5 MB