97. Interleaving String
Problem
Decide whether s3 can be formed by interleaving s1 and s2: splitting both into pieces and alternating them while keeping the characters of each in their original order.
Example: s1 = "aabcc", s2 = "dbbca": s3 = "aadbbcbcac" → true; s3 = "aadbbbaccc" → false
Constraints: follow-up: O(len(s2)) extra space.
dp[i][j] = s3[:i+j] is an interleaving of s1[:i] and s2[:j]: true if (dp[i−1][j] and s1[i−1] == s3[i+j−1]) or (dp[i][j−1] and s2[j−1] == s3[i+j−1]).
Complexity: O(m·n).
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 = [False] * (n + 1)
for i in range(m + 1):
for j in range(n + 1):
if i == 0 and j == 0:
dp[j] = True
continue
from_s1 = i > 0 and dp[j] and s1[i - 1] == s3[i + j - 1]
from_s2 = j > 0 and dp[j - 1] and s2[j - 1] == s3[i + j - 1]
dp[j] = from_s1 or from_s2
return dp[n]
assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac") is True
assert Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc") is False
assert Solution().isInterleave("", "", "") is True
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length(), n = s2.length();
if (m + n != s3.length()) return false;
boolean[] dp = new boolean[n + 1];
for (int i = 0; i <= m; i++)
for (int j = 0; j <= n; j++) {
if (i == 0 && j == 0) { dp[j] = true; continue; }
boolean a = i > 0 && dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);
boolean b = j > 0 && dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);
dp[j] = a || b;
}
return dp[n];
}
}
func isInterleave(s1 string, s2 string, s3 string) bool {
m, n := len(s1), len(s2)
if m+n != len(s3) {
return false
}
dp := make([]bool, n+1) // dp[j]: s1[:i] and s2[:j] interleave to s3[:i+j]
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 && j == 0 {
dp[j] = true
continue
}
fromS1 := i > 0 && dp[j] && s1[i-1] == s3[i+j-1]
fromS2 := j > 0 && dp[j-1] && s2[j-1] == s3[i+j-1]
dp[j] = fromS1 || fromS2
}
}
return dp[n]
}