leetcode: Scramble String

来源:互联网 发布:桌面记事本便签软件 编辑:程序博客网 时间:2024/05/29 04:32

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[i][j][k],

当F[i][j][k]=true时,表示S1[i..i+k-1] == S2[j..j+k-1]。

用白话表达:F[i][j][k]记录的是S1从i开始k个字符与S2从j开始k个字符是否为Scramble String。


最简单的情况为k=1时,即S1[i]与S2[j]是否为Scramble String。

因此F[i][j][1] = S1[i] == S2[j]。


当K=2时,

F[i][j][2] = (F[i][j][1] && F[i+1][j+1][1]) || (F[i][j+1][1] && F[i+1][j][1])。

F[i][j][1] && F[i+1][j+1][1]表达的是 S1[i] == S2[j] && S1[i+1]==S2[j+1](例如:“AC”和“AC”),如果这个条件满足,那么S1[i..i+1]与S2[j..j+1]自然为Scramble String,即F[i][j][2] = true。

F[i][j+1][1] && F[i+1][j][1]表达的是S1[i+1] == S2[j] && S1[i] == S2[j + 1] (例如: “AB”和“BA”),同样如果该条件满足,F[i][j][2] = true。


当K为更大的数时,同递归算法一样,我们需要枚举分割点,假设左边长度为l,即S[i..i+l-1],右边长度为k-l,即S[i+l..i+k-1]。

同样存在两种情况,S1左 = S2左 && S1右 = S2右 或者 S1左 = S2右 && S1右 = S2左。


少了一对括号,调了半天!!

class Solution {public:    bool isScramble(string s1, string s2) {        if( s1.size() != s2.size())            return false;        const int N = s1.size();        bool dp[N][N][N+1];        memset( dp, false, sizeof(dp));        for( int i = 0; i < N; ++i){            for( int j = 0; j < N; ++j){                dp[i][j][1] = s1[i] == s2[j];            }        }        for( int k = 1; k <= N; ++k){            for( int i = 0; i + k <= N; ++i){                for( int j = 0; j + k <= N; ++j){                    for( int l = 1; l < k; ++l){                        if( (dp[i][j][l] && dp[i+l][j+l][k-l]) || ( dp[i+l][j][k-l] && dp[i][j+k-l][l])){                            dp[i][j][k] = true;                            break;                        }                    }                }            }        }        return dp[0][0][N];    }};


0 0
原创粉丝点击