1
+ /*
2
+
3
+ Date: Jan 3, 2015
4
+ Problem: Interleaving String
5
+ Difficulty: Medium
6
+ Source: https://oj.leetcode.com/problems/interleaving-string/
7
+ Notes:
8
+ Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
9
+ For example,
10
+ Given:
11
+ s1 = "aabcc",
12
+ s2 = "dbbca",
13
+ When s3 = "aadbbcbcac", return true.
14
+ When s3 = "aadbbbaccc", return false.
15
+
16
+ Solution: 1. dp. O(MN) time & space. 'dp[i][j] == true' means that there is at least one way to construct
17
+ the string s3[0...i+j-1] by interleaving s1[0...j-1] and s2[0...i-1].
18
+ */
19
+
20
+ public class Solution {
21
+ public boolean isInterleave_1 (String s1 , String s2 , String s3 ) {
22
+ int l1 = s1 .length (), l2 = s2 .length (), l3 = s3 .length ();
23
+ if (l1 == 0 ) return s2 .compareTo (s3 ) == 0 ;
24
+ if (l2 == 0 ) return s1 .compareTo (s3 ) == 0 ;
25
+ if (l1 + l2 != l3 ) return false ;
26
+ boolean [][] dp = new boolean [l1 +1 ][l2 +1 ];
27
+ dp [0 ][0 ] = true ;
28
+ for (int i = 1 ; i <= l1 ; ++i ) {
29
+ dp [i ][0 ] = dp [i -1 ][0 ] && (s1 .charAt (i -1 ) == s3 .charAt (i -1 ));
30
+ }
31
+ for (int j = 1 ; j <= l2 ; ++j ) {
32
+ dp [0 ][j ] = dp [0 ][j -1 ] && (s2 .charAt (j -1 ) == s3 .charAt (j -1 ));
33
+ }
34
+ for (int i = 1 ; i <= l1 ; ++i ) {
35
+ for (int j = 1 ; j <= l2 ; ++j ) {
36
+ if (s1 .charAt (i - 1 ) == s3 .charAt (i +j -1 )) dp [i ][j ] = dp [i -1 ][j ];
37
+ if (s2 .charAt (j - 1 ) == s3 .charAt (i +j -1 )) dp [i ][j ] = dp [i ][j ] | dp [i ][j -1 ];
38
+ }
39
+ }
40
+ return dp [l1 ][l2 ];
41
+ }
42
+ public boolean isInterleave (String s1 , String s2 , String s3 ) {
43
+ int l1 = s1 .length (), l2 = s2 .length (), l3 = s3 .length ();
44
+ if (l1 == 0 ) return s2 .compareTo (s3 ) == 0 ;
45
+ if (l2 == 0 ) return s1 .compareTo (s3 ) == 0 ;
46
+ if (l1 + l2 != l3 ) return false ;
47
+ boolean [] dp = new boolean [l2 +1 ];
48
+ dp [0 ] = true ;
49
+ for (int j = 1 ; j <= l2 ; ++j ) {
50
+ dp [j ] = dp [j -1 ] && (s2 .charAt (j -1 ) == s3 .charAt (j -1 ));
51
+ }
52
+ for (int i = 1 ; i <= l1 ; ++i ) {
53
+ dp [0 ] = dp [0 ] && (s1 .charAt (i -1 ) == s3 .charAt (i -1 ));
54
+ for (int j = 1 ; j <= l2 ; ++j ) {
55
+ boolean before = dp [j ]; dp [j ] = false ;
56
+ if (s1 .charAt (i - 1 ) == s3 .charAt (i +j -1 )) dp [j ] = before ;
57
+ if (s2 .charAt (j - 1 ) == s3 .charAt (i +j -1 )) dp [j ] = dp [j ] | dp [j -1 ];
58
+ }
59
+ }
60
+ return dp [l2 ];
61
+ }
62
+ }
0 commit comments