[leetcode] Scramble String

ivycha發表於2013-04-02
Scramble StringApr 30 '12

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.

這道題是3維DP問題,f[len][i][j]表示分別從s1中下標為i的元素以及s2中下標為j的元素開始,長度為len的兩端子字串是否符合Scramble String,接著將長度為len的問題轉化為長度為leftsize與rightsize的兩個字串的問題。不要忘記初始化哦~

class Solution {
    bool f[100][100][100];
public:
    bool isScramble(string s1, string s2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s1.size()!=s2.size())
            return false;
        for(int i=0; i<s1.size(); i++)
            for(int j=0; j<s2.size(); j++)
                f[1][i][j]=(s1[i]==s2[j]);
        for(int len=2; len<=s1.size(); len++)
        {
            for(int s1beg=0; s1beg<s1.size(); s1beg++)
            {
                int s1end=s1beg+len-1;
                if(s1end>=s1.size())
                    break;
                for(int s2beg=0; s2beg<s2.size(); s2beg++)
                {
                    int s2end=s2beg+len-1;
                    if(s2end>=s2.size())
                        break;
                    f[len][s1beg][s2beg]=false;
                    for(int s1mid=s1beg; s1mid<s1end; s1mid++)
                    {
                        int leftsize=s1mid-s1beg+1;
                        int rightsize=len-leftsize;
                        int s2mid=s2beg+leftsize-1;
                        bool res1=f[leftsize][s1beg][s2beg] && f[rightsize][s1mid+1][s2mid+1];
                        s2mid=s2end-leftsize;
                        bool res2=f[leftsize][s1beg][s2mid+1] && f[rightsize][s1mid+1][s2beg];
                        f[len][s1beg][s2beg]=f[len][s1beg][s2beg] || res1 ||res2;
                    }
                }
            }
        }
        return f[s1.size()][0][0];
    }
};

相關文章