Recursion with some cutting
1. value
2. length
3. equals
public boolean isScramble(String s1, String s2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (s1==null || s2==null || s1.length()!=s2.length()) return false;
if (s1.equals(s2)) return true;
int len = s1.length();
int value1=0, value2=0;
for (int i=0; i<len; i++) {
value1 += s1.charAt(i) - '0';
value2 += s2.charAt(i) - '0';
}
if (value1 != value2) return false;
for (int i=1; i<len; i++) {
if (isScramble(s1.substring(0,i), s2.substring(0,i)) && isScramble(s1.substring(i), s2.substring(i))) {
return true;
}
if (isScramble(s1.substring(0, i), s2.substring(len-i)) && isScramble(s1.substring(i), s2.substring(0, len-i))) {
return true;
}
}
return false;
}
DP solution: 3D DP
public boolean isScramble(String s1, String s2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (s1==null || s2==null || s1.length()!=s2.length()) return false;
if (s1.length()==0) return true;
int len = s1.length();
boolean[][][] M = new boolean[len][len][len+1];
for (int i=0; i<len; i++) {
for (int j=0; j<len; j++) {
M[i][j][1] = s1.charAt(i)==s2.charAt(j);
}
}
for (int L=2; L<=len; L++) {
for (int i=0; i<len-L+1; i++) {
for (int j=0; j<len-L+1; j++) {
for (int k=1; k<L; k++) {
M[i][j][L] |= M[i][j][k] && M[i+k][j+k][L-k] || M[i][j+L-k][k] && M[i+k][j][L-k];
}
}
}
}
return M[0][0][len];
}
No comments:
Post a Comment