Below is one possible representation of s1 =
"great"
:
great / \ gr eat / \ / \ g r e at / \ a tTo 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 tWe 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 aWe 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 string s1 and s2 are scramble strings, there must be a point that breaks s1 to two parts s11, s12, // and a point that breaks s2 to two parts, s21, s22, and isScramble(s11, s21) && isScramble(s12, s22) is true, // or isScramble(s11, s22) && isScramble(s12, s21) is true. // So we can make it recursively. // We just break s1 at different position to check if there exists one position satisfies the requirement. // Some checks are needed otherwise it will time out. // For example, if the lengths of two strings are different, they can’t be scramble. // And if the characters in two strings are different, they can’t be scramble either. // Step 1. Check lengths. if (s1.length() != s2.length()) return false; // Step 2. Check equality. if (s1.equals(s2)) return true; int L = s1.length(); // Step 3. Check if with the same characters int[] c = new int[256]; for (int i = 0; i < L; i++) { c[s1.charAt(i)]++; c[s2.charAt(i)]--; } for (int i = 0; i < 256; i++) if (c[i] != 0) return false; // Step 4. Check every dividing point for (int i = 1; i < L; i++) { String s11 = s1.substring(0, i); String s12 = s1.substring(i, L); String s21 = s2.substring(0, i); String s22 = s2.substring(i, L); if (isScramble(s11, s21) && isScramble(s12, s22)) return true; s21 = s2.substring(0, L - i); s22 = s2.substring(L - i, L); if (isScramble(s11, s22) && isScramble(s12, s21)) return true; } return false; } }
No comments:
Post a Comment