给定三个字符串 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n = s1.size();
int m = s2.size();
int t = s3.size();
//dp[i][j] : s1的前i个与s2的前j个字符能否构成s3的前i+j
vector <vector<int>> dp = vector (n + 1, vector<int> (m + 1, false));
if (n + m != t) return false;
dp[0][0] = true;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
int p = i + j - 1;
if (i > 0) {
dp[i][j] |= dp[i - 1][j] && s1[i -1] == s3[p];
}
if (j > 0) {
dp[i][j] |= dp[i][j - 1] && s2[j - 1] == s3[p];
}
}
}
return dp[n][m];
}
};