首页 > 代码库 > [Leetcode] Scramble String

[Leetcode] 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.

 

Solution:

 1 public class Solution { 2     public boolean isScramble(String s1, String s2) { 3         if(s1.equals(s2)) 4             return true; 5         int l1=s1.length(); 6         int l2=s2.length(); 7         if(l1!=l2) 8             return false; 9         if(l1==0)10             return true;11         if(l1==1)12             return s1.equals(s2);13         char[] c_s1=s1.toCharArray();14         char[] c_s2=s2.toCharArray();15         Arrays.sort(c_s1);16         Arrays.sort(c_s2);17         for(int i=0;i<c_s1.length;++i){18             if(c_s1[i]!=c_s2[i])19                 return false;20         }21         boolean b=false;22         for(int i=1;i<l1&&!b;++i){23             String s11=s1.substring(0,i);24             String s12=s1.substring(i);25             String s21=s2.substring(0,i);26             String s22=s2.substring(i);27             b=isScramble(s11, s21)&&isScramble(s12, s22);28             if(!b){29                 String s31=s2.substring(0, l1-i);30                 String s32=s2.substring(l1-i);31                 b=isScramble(s11, s32)&&isScramble(s12, s31);32             }33         }34         return b;35     }36 }

 

[Leetcode] Scramble String