[LeetCode] 97. Interleaving String

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

Thought process:
  1. Sub-problem: find whether s3[0, i + j] can be formed by the interleaving of s1[0, i] and s2[0, j].
  2. Function: 
    1. If s3[i + j] comes from s1[i], then f[i][j] = f[i - 1][j].
    2. If s3[i + j] comes from s2[j], then f[i][j] = f[i][j - 1].
  3. Initialization: f[0][0] = true. f[i][0] = true if s1[0, i] equals s3[0, i]. f[0][j] = true if s2[0, j] equals s3[0, j].
  4. Answer: f[s1.length][s2.length].
Check if s3.length == s1.length + s2.length before iterating through the matrix to prevent array index out of bound exception.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        int length1 = s1.length();
        int length2 = s2.length();
        if (s3.length() != length1 + length2) {
            return false;
        }
        
        boolean[][] f = new boolean[length1 + 1][length2 + 1];
        
        f[0][0] = true;
        for (int i = 1; i <= length1; i++) {
            if (s1.charAt(i - 1) == s3.charAt(i - 1)) {
                f[i][0] = true;
            } else {
                break;
            }
        }
        for (int i = 1; i <= length2; i++) {
            if (s2.charAt(i - 1) == s3.charAt(i - 1)) {
                f[0][i] = true;
            } else {
                break;
            }
        }
        
        for (int i = 1; i <= length1; i++) {
            for (int j = 1; j <= length2; j++) {
                f[i][j] = (s1.charAt(i - 1) == s3.charAt(i + j - 1) && f[i - 1][j]) || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && f[i][j - 1]);
            }
        }
        
        return f[length1][length2];
    }
}
Time complexity:
Say m = s1.length and n = s2.length, the time complexity is O(mn).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[HackerRank] Roads and Libraries

[LeetCode] 631. Design Excel Sum Formula