|
1 |
| -public class InterleavingString { |
2 |
| - public static void main(String[] args) { |
3 |
| - System.out.println(isInterleave("aabcc", "dbbca", "aadbbcbcac")); |
4 |
| - } |
| 1 | +// https://leetcode.com/problems/interleaving-string |
| 2 | +// T: O(n * m) |
| 3 | +// S: O(min(m, n)) |
5 | 4 |
|
6 |
| - public static boolean isInterleave(String s1, String s2, String s3) { |
| 5 | +public class InterleavingString { |
| 6 | + public boolean isInterleave(String s1, String s2, String s3) { |
7 | 7 | if (s1.length() + s2.length() != s3.length()) return false;
|
8 |
| - for (int i = 0, j = 0, t = 0 ; i <= s1.length() && j <= s2.length() && t < s3.length() ; t++) { |
9 |
| - if (i < s1.length() && s3.charAt(t) == s1.charAt(i)) i++; |
10 |
| - else if (j < s2.length() && s3.charAt(t) == s2.charAt(j)) j++; |
11 |
| - else return false; |
| 8 | + if (s1.length() < s2.length()) { |
| 9 | + String temp = s1; |
| 10 | + s1 = s2; |
| 11 | + s2 = temp; |
12 | 12 | }
|
13 |
| - return true; |
| 13 | + |
| 14 | + final int rows = s1.length() + 1, columns = s2.length() + 1; |
| 15 | + final boolean[] dp = new boolean[columns]; |
| 16 | + |
| 17 | + for (int row = 0 ; row < rows ; row++) { |
| 18 | + for (int column = 0 ; column < columns ; column++) { |
| 19 | + if (row == 0 && column == 0) { |
| 20 | + dp[column] = true; |
| 21 | + } else if (row == 0) { |
| 22 | + dp[column] = dp[column - 1] && s2.charAt(column - 1) == s3.charAt(row + column - 1); |
| 23 | + } else if (column == 0) { |
| 24 | + dp[column] = dp[column] && s1.charAt(row - 1) == s3.charAt(row + column - 1); |
| 25 | + } else { |
| 26 | + dp[column] = (s1.charAt(row - 1) == s3.charAt(row + column - 1) && dp[column]) |
| 27 | + || (s2.charAt(column - 1) == s3.charAt(row + column - 1) && dp[column - 1]); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return dp[columns - 1]; |
14 | 33 | }
|
15 | 34 | }
|
0 commit comments