Leetcode 97. Interleaving String
Given strings s1, s2, and s3, check whether s3 is formed by an interleaving of s1 and s2.
An interleaving of two strings s and t is a configuration where s and t are divided into n and m subsequences respectively, such that:
s = s1 + s2 + ... + s_nt = t1 + t2 + ... + t_m|n - m| ≤ 1The interleaved string would have all these subsequences in order but bother s and t are not reordered.
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"Output: true
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"Output: falses3 is not equal to the sum of the lengths of s1 and s2, return false right away.dp[i][j] means if s3 up to i+j can be formed by interleaving s1 up to i and s2 up to j.
dp[0][0] = true because an empty string can be formed from two empty strings.i, j:
dp[i-1][j] is true and s1[i-1] == s3[i+j-1], then set dp[i][j] to true.dp[i][j-1] is true and s2[j-1] == s3[i+j-1], then set dp[i][j] to true.dp[len(s1)][len(s2)] which tells if the full s3 can be formed by interleaving the entire s1 and s2.#include <iostream>
#include <vector>
#include <string>
bool isInterleave(std::string s1, std::string s2, std::string s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
// Edge case check
if (len1 + len2 != len3) {
return false;
}
// Initialize the DP table
std::vector<std::vector<bool>> dp(len1 + 1, std::vector<bool>(len2 + 1, false));
dp[0][0] = true;
// Fill the DP table
for (int i = 0; i <= len1; ++i) {
for (int j = 0; j <= len2; ++j) {
if (i > 0) {
dp[i][j] = dp[i][j] || (dp[i-1][j] && s1[i-1] == s3[i+j-1]);
}
if (j > 0) {
dp[i][j] = dp[i][j] || (dp[i][j-1] && s2[j-1] == s3[i+j-1]);
}
}
}
return dp[len1][len2];
}
int main() {
std::string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac";
std::cout << (isInterleave(s1, s2, s3) ? "true" : "false") << std::endl; // should return true
s1 = "aabcc"; s2 = "dbbca"; s3 = "aadbbbaccc";
std::cout << (isInterleave(s1, s2, s3) ? "true" : "false") << std::endl; // should return false
return 0;
}
s1 and (m) is the length of s2.By following the above plan, the problem can be solved efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?