Chinaunix首页 | 论坛 | 博客
  • 博客访问: 225051
  • 博文数量: 41
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 407
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-27 13:42
文章分类

全部博文(41)

文章存档

2016年(1)

2015年(18)

2014年(22)

我的朋友

分类: C/C++

2014-09-17 09:36:59

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.

*********************************************************************************

分析:

    状态转移方程-f[n][i][j]表示以s1[i]为起点和以s2[j]为起点的长度为n的两个字符串是否为Scramble String,那么如果f[N][i][j]就表示最终结果


*********************************************************************************

代码:

    bool isScramble(string s1, string s2) {
        const int N = s1.size();
        if (s1.size() != s2.size()) return false;
    
        bool f[N + 1][N][N];
        fill_n(&f[0][0][0], (N + 1) * N * N, false);
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
                f[1][i][j] = s1[i] == s2[j];
    
        for (int n = 2; n <= N; n++) {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    for (int k = 1; k < n; k++) {
                        if ((f[k][i][j] && f[n - k][i + k][j + k]) ||
                                    (f[k][i][j + n - k] && f[n - k][i + k][j])) {
                            f[n][i][j] = true;
                            break;
                        }
                    }
                }
            }
        }
        return f[N][0][0];
    }

阅读(1317) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~