forked from hrsvrdhn/DP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterleavingStrings.java
More file actions
56 lines (50 loc) · 1.61 KB
/
InterleavingStrings.java
File metadata and controls
56 lines (50 loc) · 1.61 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.*;
import java.io.*;
public class InterleavingStrings {
//returns 1 if C can be formed by interleaving A and B, otherwise 0
public static int isInterleave(String A, String B, String C) {
if(C.length() != A.length() + B.length()) {
return 0;
}
boolean[][] match = new boolean[A.length() + 1][B.length() + 1];
for(int i = 1; i <= A.length(); i++){
if(A.charAt(i - 1) == C.charAt(i - 1)) {
match[i][0] = true;
}
else {
break;
}
}
for(int i = 1; i <= B.length(); i++){
if(B.charAt(i-1) == C.charAt(i-1)) {
match[0][i] = true;
}
else {
break;
}
}
for(int i = 1; i <= A.length(); i++){
char ai = A.charAt(i - 1);
for(int j = 1; j <= B.length(); j++){
char bi = B.charAt(j - 1);
char ci = C.charAt(i + j - 1);
if(ai == ci) {
match[i][j] = (match[i - 1][j] || match[i][j]);
}
if(bi == ci) {
match[i][j] = (match[i][j - 1] || match[i][j]);
}
}
}
if(match[A.length()][B.length()]) {
return 1;
}
return 0;
}
public static void main(String args[]) {
String A = "aabcc";
String B = "dbbca";
System.out.println(isInterleave(A, B, "aadbbcbcac"));
System.out.println(isInterleave(A, B, "aadbbbaccc"));
}
}