您的位置:首页 > 其它

Scramble String

2015-06-16 23:14 211 查看
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.

解题思路:简单的四维DP。

dp[i1][j1][i2][j2]表示s1的i1->j1的子串和s2的i2->j2的子串是否匹配。

class Solution {
public:
    bool isScramble(string s1, string s2) {
        int n = s1.length();
        bool dp[30][30][30][30];
        memset(dp, false, sizeof(dp));
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < n; ++j) {
                if(s1[i] == s2[j]) {
                    dp[i][i][j][j] = true;
                }
            }
        }
        for(int k = 1; k < n; ++k) {
            for(int i1 = 0; i1 + k < n; ++i1) {
                for(int i2 = 0; i2 + k < n; ++i2) {
                    int j1 = i1 + k;
                    int j2 = i2 + k;
                    for(int l = i1; l < j1; ++l) {
                        dp[i1][j1][i2][j2] |= (dp[i1][l][i2][i2+l-i1]&dp[l+1][j1][i2+l-i1+1][j2]);
                        dp[i1][j1][i2][j2] |= (dp[i1][l][j2-(l-i1)][j2]&dp[l+1][j1][i2][i2+j1-l-1]);
                    }
                }
            }
        }
        return dp[0][n-1][0][n-1];
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: