




Sponsored
Sponsored
This approach uses a dynamic programming table to ascertain whether the third string, s3, is an interleaving of s1 and s2. We use a 2D DP array dp[i][j] which signifies if s3[0:i+j] is an interleaving of s1[0:i] and s2[0:j]. A bottom-up approach is taken to fill this table.
Time Complexity: O(n * m), where n and m are the lengths of s1 and s2, respectively.
Space Complexity: O(n * m), required for the dp array.
1#include <vector>
2#include <string>
3
4class Solution {
5public:
6    bool isInterleave(std::string s1, std::string s2, std::string s3) {
7        int n = s1.size();
8        int m = s2.size();
9        int l = s3.size();
10        if (n + m != l) return false;
11        std::vector<std::vector<bool>> dp(n + 1, std::vector<bool>(m + 1, false));
12        dp[0][0] = true;
13        for (int i = 0; i <= n; ++i) {
14            for (int j = 0; j <= m; ++j) {
15                if (i > 0) {
16                    dp[i][j] = dp[i][j] || (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
17                }
18                if (j > 0) {
19                    dp[i][j] = dp[i][j] || (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
20                }
21            }
22        }
23        return dp[n][m];
24    }
25};This C++ implementation mirrors the C implementation but uses the std::vector class to maintain the DP table. It iterates through potential substrings, updating whether the current part of s3 can be formed by interleaving parts of s1 and s2.
This recursive approach tries to construct the interleaved string by attempting to use characters from s1 and s2 to match each character of s3. To optimize, memoization is applied to avoid recalculating results for the same subproblems.
Time Complexity: O(n * m), due to memoization allowing only one calculation per subproblem.
Space Complexity: O(n * m) for the memoization table.
1
The JavaScript function employs recursion with memoization, stored in a Map object, to try forming s3 incrementally from s1 and s2 by sequentially validating or skipping characters.