Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created February 28, 2014 06:26
Show Gist options
  • Select an option

  • Save wayetan/9266290 to your computer and use it in GitHub Desktop.

Select an option

Save wayetan/9266290 to your computer and use it in GitHub Desktop.
Scramble String
/**
* Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
* Below is one possible representation of s1 = "great":
* great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
* To scramble the string, we may choose any non-leaf node and swap its two children.
* For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
* rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
* We say that "rgeat" is a scrambled string of "great".
* Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
* rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
* We say that "rgtae" is a scrambled string of "great".
* Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
*/
public class Solution {
public boolean isScramble(String s1, String s2) {
if(s1.length() != s2.length())
return false;
if(s1.length() == 0 && s2.length() == 0)
return true;
boolean[][][] scramble = new boolean[s1.length()][s2.length()][s1.length()];
for(int i = 0; i < s1.length(); i++) {
for(int j = 0; j < s2.length(); j++) {
scramble[i][j][0] = (s1.charAt(i) == s2.charAt(j));
}
}
for(int l = 1; l < s1.length(); l++) {
for(int i = 0; i < s1.length() - l; i++) {
for(int j = 0; j < s2.length() - l; j++) {
for(int k = 0; k < l; k++) {
if((scramble[i][j][k] && scramble[i + k + 1][j + k + 1][l - k - 1]) || (scramble[i][j + l - k][k] && scramble[i + k + 1][j][l - k - 1]))
scramble[i][j][l] = true;
}
}
}
}
return scramble[0][0][s1.length() - 1];
}
}
public class Solution {
public boolean isScramble(String s1, String s2) {
if (s1.length() != s2.length())
return false;
if (s1.equals(s2))
return true;
String ts1, ts2;
char[] c_s1 = s1.toCharArray();
Arrays.sort(c_s1);
ts1 = new String(c_s1);
char[] c_s2 = s2.toCharArray();
Arrays.sort(c_s2);
ts2 = new String(c_s2);
if(!ts1.equals(ts2))
return false;
for(int isep = 1; isep < s1.length(); isep++) {
String seg11 = s1.substring(0, isep);
String seg12 = s1.substring(isep);
// see if forward order is OK
String seg21 = s2.substring(0, isep);
String seg22 = s2.substring(isep);
if(isScramble(seg11, seg21) && isScramble(seg12, seg22))
return true;
// see if backward order is OK
seg21 = s2.substring(s2.length() - isep);
seg22 = s2.substring(0, s2.length() - isep);
if(isScramble(seg11, seg21) && isScramble(seg12, seg22))
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment