Interleaving String

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 boolean isInterleave(String s1, String s2, String s3) {
        int n = s1.length(), m = s2.length(), l = s3.length();
        if (n + m != l)
            return false;
        boolean dp[][] = new boolean[n + 1][m + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                // Base cases start
                if (i == 0 && j == 0)
                    dp[i][j] = true;
                else if (i == 0) {
                    if (s2.charAt(j - 1) == s3.charAt(j - 1))
                        dp[i][j] = dp[i][j - 1];
                } else if (j == 0) {
                    if (s1.charAt(i - 1) == s3.charAt(i - 1))
                        dp[i][j] = dp[i - 1][j];
                } // base cases end
                else if (s1.charAt(i - 1) == s3.charAt(i + j - 1) && s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
                    dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
                } else if (s1.charAt(i - 1) == s3.charAt(i + j - 1))
                    dp[i][j] = dp[i - 1][j];
                else if (s2.charAt(j - 1) == s3.charAt(i + j - 1))
                    dp[i][j] = dp[i][j - 1];
                else
                    dp[i][j] = false;
            }
        }
        return dp[n][m];
    }
}

Last updated