[leetcode#87] Scramble String

Source: Internet
Author: User

problem:

Given A string S1, we may represent it as a binary tree by partitioning it to the Non-empty substrings Recursivel Y.

Below is one possible representation of S1 = "great" :

    Great   /      gr    eat/\    /  g   r  E   at           /           a   t

To scramble the string, we are choose any non-leaf node and swap it to the children.

For example, if we choose the node "gr" and swaps its-children, it produces a scrambled string "rgeat" .

    Rgeat   /      RG    eat/\    /  r   G  e   at           /           a   t

We say is "rgeat" a scrambled string of "great" .

Similarly, if we continue to swap the children of nodes "eat" "at" and, it produces a scrambled string "rgtae" .

    Rgtae   /      RG    tae/\    /  r   G  ta  e       /       t   a

We say is "rgtae" a scrambled string of "great" .

Given strings S1 and S2 of the same length, determine if S2 is a scrambled string of S1.

Analysis:

The instant idea of this problem are easy.
Apparently, you use a DFS method to constuct the scrmble string of S1. Once detect out a scramble string S1 equal to S2. Then you can say S2 is the scramble string of S1.

Inefficient solution 1:

 Public classSolution { Public Booleanisscramble (string s1, string s2) {if(S1 = =NULL&& S2 = =NULL)            return true; if(S1 = =NULL|| S2 = =NULL)            return false; if(S1.length ()! =s2.length ())return false;  for(inti = 0; I < s1.length (); i++) {List<String> left = swaphelper (s1.substring (0, i)); List<String> right =Swaphelper (s1.substring (i)); if(Combine (left, right, S2))return true; }        return false; }            PrivateArraylist<string>Swaphelper (String s) {ArrayList<String> ret =NewArraylist<string> (); if(s.length () = = 0) {Ret.add (""); returnret; }        if(s.length () = = 1) {Ret.add (s); returnret; }         for(inti = 0; I < s.length (); i++) {List<String> left = swaphelper (s.substring (0, i)); List<String> right =Swaphelper (s.substring (i));  for(String l_part:left) { for(String r_part:right) {ret.add (L_part+R_part); Ret.add (R_part+L_part); }            }        }        returnret; }            Private BooleanCombine (list<string> left, list<string>Right , String S2) {         for(String l_part:left) { for(String r_part:right) {if(S2.equals (l_part+r_part) | | s2.equals (R_part +L_part)) return true; }        }        return false; } }

ImprovedAnalysis:

Even though above solution is right, it faces the problem of TLE. To search forThe scramble string collections, we have too much uncessary search, which are quite expensive in Thisproblem. Actually, we could use a more easy-to-solve ThisProblem. and ThisIs a typical recursive problem. Since according to the definition of the problem. The constructing process of possible scramble string is a recursive process. The Process:great/GR Eat/ \    /G R e at/a T=rgeat/RG Eat/ \    /R G E at/a tlet US randomly choose an indexIOn the string S1. Then we treat s[0, I] as left-sub tree and S[i+1, len-1] as right sub-Tree. Then, acoording to the process of constructing a scramle String, we could swap them (or not swap them) to get a scramble s Tring. And furtherly, we could keep on doing ThisTransform over let-sub tree and right-Sub Tree, which would also produce the scramble strings of the orginal string s.this is recursive are so clearly!!!But how could to make it more efficiently during the process of searching.=>if you solely DoScramble string transformation over a string, you still need to Doa lot of uncessary search. A -To fix ThisProblem is to include the information from S2. And then use the S2 ' s information to cut-off uncessary search branches.Key point:iff S1 and S2 is scramble strings with all other, there must is a point (swap point) one S1 and S2, to Inde X"I" to cut-off the string into the separate substrings (sub-tree). s1[0, I) s1[i, len-1]s2[0, I) s2[i, len-1]//When the left-sub tree and Right-sub tree of S1 not need to swap positionor s1[0, I) s1[i, len-1]s2[len-I, len-1] s2[0, len-i)//When then left-sub tree and Right-sub tree of the S1 need to swap position for(inti = 1; i < Len; i++) {String S11= s1.substring (0, i); String S12=s1.substring (i, Len); String S21= s2.substring (0, i); String S22=s2.substring (i, Len); if(Isscramble (S11, S21) &&isscramble (S12, S22))return true; S11= s1.substring (0, Len-bi); S12= S1.substring (Len-I, Len); if(Isscramble (S11, S22) &&isscramble (S12, S21))return true;}------------------------------------------------------------------------------------ for(inti = 1; i < Len; i++) Note:we must start from I= 1, otherwise the same string would keep on entering to isscramble (), and result in Infinite loop. Apparently, the above search cost was very high!!! But we could find a method to DoProperly cut-off during the process.1.if(S1.length ()! = S2.length ()), it is impossible forS1 and S2 is scramble string with all other. ( Thisis the test forS1 and S2 Just enter the isscramble string) in the afterward calls, ThisSituation would not happen, since we control the S1 and S2 's length must equal with all other through:string S11 = S1.sub String (0, i); String S12=s1.substring (i, Len); String S21= s2.substring (0, i); String S22=s2.substring (i, Len); or S11= s1.substring (0, Len-i); S12= S1.substring (Len-I, Len); Note: ThisKind of base Caseis very common in elegant recursive solution. It also tackle the Caseof inital illegal call.2. Most important base Case:if(s1.equals (S2)). It means S1 must be the scramble string of S2. The worst Caseis we reach ThisBase CaseAs- characters.s1= "a"S2= "a" 3. The count of each characters should is equal.//This cut-off policy is super useful, it could greatly improve efficiency. for(inti = 0; i < Len; i++) {Count[s1.charat (i)-' A ']++; Count[s2.charat (i)-' A ']--;}

Upgraded Solution:

 Public classSolution { Public Booleanisscramble (string s1, string s2) {if(S1.length ()! =s2.length ())return false; if(s1.equals (S2))return true; int[] Count =New int[26]; intLen =s1.length ();  for(inti = 0; i < Len; i++) {Count[s1.charat (i)-' A ']++; Count[s2.charat (i)-' A ']--; }         for(inti = 0; I < 26; i++) {            if(count[i]! = 0)                return false; }         for(inti = 1; i < Len; i++) {String S11= s1.substring (0, i); String S12=s1.substring (i, Len); String S21= s2.substring (0, i); String S22=s2.substring (i, Len); if(Isscramble (S11, S21) &&isscramble (S12, S22))return true; S11= s1.substring (0, Len-i); S12= S1.substring (Len-I, Len); if(Isscramble (S11, S22) &&isscramble (S12, S21))return true; }        return false; }}

[leetcode#87] Scramble String

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.