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.

思路:

动规。用result[i][j][k]表示s[i..i+k-1]与s[j..j+k-1]是否相等。

代码:

 1     bool isScramble(string s1, string s2) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         if(s1.length() != s2.length())
 5             return false;
 6         int len = s1.length();
 7         bool result[len][len][len+1];
 8         memset(result, false, sizeof(bool)*len*len*(len+1));
 9         int i,j,k,m;
10         for(i = 1; i <= len; i++){
11             for(j = 0; j <= len-i; j++){
12                 for(k = 0; k <= len-1; k++){
13                     if(i == 1)
14                         result[j][k][i] = (s1[j] == s2[k]);
15                     else{
16                         for(m = 1 ; m < i; m++){
17                             result[j][k][i] = (result[j][k][m] && result[j+m][k+m][i-m])||(result[j][k+i-m][m] && result[j+m][k][i-m]);
18                             if(result[j][k][i])
19                                 break;
20                         }                            
21                     }
22                     cout<<j<<" "<<k<<" "<<i<<": "<<result[j][k][i]<<endl;
23                 }
24             }   
25         }
26         return result[0][0][len];
27     }

 

posted on 2013-11-23 10:51  waruzhi  阅读(216)  评论(0编辑  收藏  举报

导航