B1cffc150d44f41b72795ce125d52a6d
(难度Hard)Problem 87. Scramble String(爬行字符串)

链接

Scramble String - LeetCode

难度等级

Hard

题干

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,判断s2能否通过s1爬行操作获得。

爬行操作是指将字符串分成两个部分,然后翻转两个部分的顺序。

比如:great 分成gr和eat,翻转顺序之后得到eatgr。

但是需要注意的是,翻转操作是可以递归进行的。参考上图的例子:

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

我们可以把字符串持续拆分,然后选择当中任意一个非叶子节点进行翻转。譬如说,我们可以选择at节点,翻转之后得到greta。

并且翻转操作可以执行多次,以及每次拆分的时候,并不是要求均分的(作者本人因为没有注意到这点被卡了1h)。

样例

Example 1:

Input: s1 = “great”, s2 = “rgeat”
Output: true
top Created with Sketch.