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.


从题目示意图可以看到,如果s1是s2的一个scramble,那必然在s1中存在一个偏移位置i把s1切分成两段 (0,i),( i + 1, s1.length() - 1)这两段,这两段的前后两种组合之一一定能和s2相对应的长度的两段形成符合scramble定义的形式。  这里i的取值范围(0, s1.length())如果I等于s1.length()则表示s1没有切分(s1直接等于s2). 

对于上边的s1的被切分出来的两段,又可以分别从头开始应用相同的分析逻辑。 

到此我们可以看出来这个问题可以分治递归解决, 但是同时注意到每层的切分都要遍历当前层所有切分位置,这样必然导致接近分治底层的基本组合情况会被多次计算,这正是动态规划要解决的问题。

最后可以得到下边的动态规划的解法,从底部开始构造,保存中间构造结果,直到把整个串都构造完毕(这时一个迭代解法,用同样的记忆法,也可以用递归来实现)。


class Solution {
public:
    bool isScramble(string s1, string s2) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len = s1.length();
        if (len != s2.length()) return false;
        bool ret[len][len][len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                ret[i][j][0] = (s1[i] == s2[j]);
            }
        }

        for (int l = 2; l <= len; l++) {
            for (int i = 0; i <= len - l; i++) {
                for (int j = 0; j <= len - l; j++) {
                    ret[i][j][l - 1] = false;
                    for (int k = 1; k < l; k++) {
                        if ((ret[i][j][k - 1] && ret[i + k][j + k][l - k - 1]) || 
                            (ret[i][j + l - k][k - 1] && ret[i + k][j][l - k - 1])) {
                            ret[i][j][l - 1] = true;
                            break;
                        }
                    }
                }
            }
        }

        return ret[0][0][len - 1];
    }

};









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值