leetcode: Scramble String

Scramble String Problem Description:

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.

Scramble String Solution and Precautions:

(1) DP: F(i, j, len) denotes whether s1[i]…s1[i+len-1] and s2[j][j+len-1] are scramble string or not  then we have the following recursive defintion:

              F(i, j, len) = Union  { F(i, j, l) and F(i + l, j + l, len – l) } OR
{ F(i + len – l, j, l) and F(i, j + l, len – l) }
for l = 1, … len – 1
OR
s1[i]…s1[i+len-1] == s2[j][j+len-1]

</div>

This issue an O(N^3) solution which could pass OJ

(2) DFS + Pruning, essentially, we adopt the same recursive definition as in (1) and do dfs, once we find a possible Scramble string match, we return. This might be faster than DP since we don’t continue once we find possible Scramble string, but DP will anyways exhaust all the possible candidates.

Scramble String Tips and Divergent thinking:

N/A

(全文完,原创文章,转载时请注明作者和出处)


(转载本站文章请注明作者和出处 烟客旅人 sigmainfy — http://www.sigmainfy.com,请勿用于任何商业用途)

</div> </div> </div>

Written on June 23, 2013