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.
Solution 1:
public boolean isScramble(String s1, String s2) { if(s1.equals(s2)) return true; // base case if(s1.length() != s2.length()) return false; int n = s1.length(); char[] s1Array = s1.toCharArray(); char[] s2Array = s2.toCharArray(); Arrays.sort(s2Array); Arrays.sort(s1Array); for(int i = 0; i < n; i++){ if(s1Array[i] != s2Array[i]) return false; } for(int i = 1; i < n;i++){ String s1pre = s1.substring(0,i); String s1suf = s1.substring(i); String s2pre = s2.substring(0, i); String s2suf = s2.substring(i); boolean result = isScramble(s1pre, s2pre) && isScramble(s1suf, s2suf); if(!result){ s2pre = s2.substring(0, s1.length() - i); s2suf = s2.substring(s1.length() - i); result = isScramble(s1pre, s2suf) && isScramble(s1suf, s2pre); } if(result) return true; } return false; }
Solution 2:
public boolean isScramble(String s1, String s2) { if(s1.equals(s2)) return true; // base case if(!isAnagram(s1, s2)) return false; int n = s1.length(); for(int i = 1; i < n;i++){ String s1pre = s1.substring(0,i); String s1suf = s1.substring(i); String s2pre = s2.substring(0, i); String s2suf = s2.substring(i); boolean result = isScramble(s1pre, s2pre) && isScramble(s1suf, s2suf); if(!result){ s2pre = s2.substring(0, s1.length() - i); s2suf = s2.substring(s1.length() - i); result = isScramble(s1pre, s2suf) && isScramble(s1suf, s2pre); } if(result) return true; } return false; } private boolean isAnagram(String s1, String s2) { if(s1.length() != s2.length()) return false; int[] table = new int[256]; int n = s1.length(); for(int i=0; i<n; i++) { table[s1.charAt(i)]++; } for(int i=0; i<n; i++) { char c = s2.charAt(i); if(--table[c] < 0) return false; } return true; }