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.

C++:
01 bool isScrambleHelper(string& s1, string& s2, int p, int q, int n, int m)
02 {
03     if(p==q)
04     {
05         if(s1[p]==s2[n])
06         {
07             return true;
08         }
09         return false;
10     }
11     int A[128];
12     for(int i=0;i<128;i++)
13     {
14         A[i]=0;
15     }
16     for(int i=p;i<=q;i++)
17     {
18         A[s1[i]]++;
19     }
20     for(int i=n;i<=m;i++)
21     {
22         A[s2[i]];
23         if(A[s2[i]]<0)
24             return false;
25     }
26     for(int i=p;i<q;i++)
27     {
28         bool a=isScrambleHelper(s1,s2,p,i,n,n+ip);
29         bool b=isScrambleHelper(s1,s2,i+1,q,n+ip+1,m);
30         if(a&&b)
31             return true;
32         a=isScrambleHelper(s1,s2,p,i,mi+p,m);
33         if(!a) continue;
34         b=isScrambleHelper(s1,s2,i+1,q,n,mi+p1);
35         if(!b) continue;
36         return true;
37     }
38     return false;
39 }
40 class Solution {
41 public:
42     bool isScramble(string s1, string s2) {
43         // Start typing your C/C++ solution below
44         // DO NOT write int main() function
45         int n=s1.size();
46         int m=s2.size();
47         if(n!=m)
48             return false;
49         return isScrambleHelper(s1,s2,0,n1,0,n1);
50     }
51 };
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s