LeetCode 97: Interleaving String Solution
Master LeetCode problem 97 (Interleaving String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
97. Interleaving String
Problem Explanation
Explanation:
To solve this problem, we can use a dynamic programming approach. We can create a 2D boolean array dp, where dp[i][j] represents whether the first i characters of s1 and the first j characters of s2 can interleavingly form the first i+j characters of s3.
The recurrence relation can be defined as follows:
- If the current character in s3 matches the current character in s1, we check if dp[i-1][j] is true.
- If the current character in s3 matches the current character in s2, we check if dp[i][j-1] is true.
The base cases are when i=0 and j=0, in which case dp[0][0] is true.
After filling up the dp array, the answer will be stored in dp[s1.length()][s2.length()]. Solution:
Solution Code
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[m+1][n+1];
dp[0][0] = true;
for (int i = 1; i <= m; i++) {
dp[i][0] = dp[i-1][0] && s1.charAt(i-1) == s3.charAt(i-1);
}
for (int j = 1; j <= n; j++) {
dp[0][j] = dp[0][j-1] && s2.charAt(j-1) == s3.charAt(j-1);
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1)) ||
(dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
}
}
return dp[m][n];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 97 (Interleaving String)?
This page provides optimized solutions for LeetCode problem 97 (Interleaving String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 97 (Interleaving String)?
The time complexity for LeetCode 97 (Interleaving String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 97 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 97 in Java, C++, or Python.