97. Interleaving String
Hard
85948FavoriteShare
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
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.length() + s2.length() != s3.length())
{
return false;
}
vector<bool> table_row(s2.length() + 1, false);
vector<vector<bool>> dp(s1.length() + 1, table_row);
for (int i = 0; i <= s1.length(); i++) {
if (s1.substr(0, i).compare(s3.substr(0, i)) == 0)
{
dp[i][0] = true;
}
}
for (int i = 0; i <= s2.length(); i++) {
if (s2.substr(0, i).compare(s3.substr(0, i)) == 0)
{
dp[0][i] = true;
}
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if (s1[i - 1] != s3[i + j - 1] && s2[j - 1] == s3[i + j - 1]) {
dp[i][j] = dp[i][j - 1];
}
if (s1[i - 1] == s3[i + j - 1] && s2[j - 1] != s3[i + j - 1]) {
dp[i][j] = dp[i - 1][j];
}
if (s1[i - 1] == s3[i + j - 1] && s2[j - 1] == s3[i + j - 1]) {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[s1.length()][s2.length()];
}
};