Monday, November 25, 2013

LeetCode Problem : Scramble String

Problem


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.

Code

bool isScr_r(string s1, string s2,int n) {
    if(s1 == s2)
        return true;
    if(n == 1)
        return false;
    string ss1(s1);
    string ss2(s2);
    sort(ss1.begin(),ss1.end());
    sort(ss2.begin(),ss2.end());
    if(ss1 != ss2)
        return false;
    for(int len = 1;len < n;++len){
        string str11 = s1.substr(0,len);
        string str12 = s1.substr(len,n - len);

        string str21 = s2.substr(0,len);
        string str22 = s2.substr(len,n - len);
        string str23 = s2.substr(n - len,len);
        string str24 = s2.substr(0,n - len);

        bool ret1 = isScr_r(str11,str21,len);
        if(ret1){
            bool ret2 = isScr_r(str12,str22,n - len);
            if(ret2)
                return true;
        }
        bool ret3 = isScr_r(str11,str23,len);
        if(ret3){
            bool ret4 = isScr_r(str12,str24,n - len);
            if(ret4)
                return true;
        }
    }
    return false;
}
bool isScramble(string s1, string s2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
    int n = s1.size();
    int m = s2.size();
    if(m != n)
        return false;
    return isScr_r(s1,s2,n);
}


No comments:

Post a Comment