随笔 - 40  文章 - 0  评论 - 48  阅读 - 13万

LeetCode 笔记系列 19 Scramble String [合理使用递归]

题目:

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.

完全没有思路。

卡了很久,最后参考这里的解释。写了一个递归的版本解决。

代码:

复制代码
public boolean isScramble(String s1, String s2) {
        // Start typing your Java solution below
        // DO NOT write main() function
       if(!isContainSameChars(s1, s2))return false;
       if(s1.equals(s2)) return true;
       for(int split = 1; split < s1.length(); split++){
           String s11 = s1.substring(0, split);
           String s12 = s1.substring(split);
           
           String s21 = s2.substring(0, split);
           String s22 = s2.substring(split);
           if(isScramble(s11, s21) && isScramble(s12, s22)) return true;
           
           s21 = s2.substring(0, s2.length() - split);
           s22 = s2.substring(s2.length() - split);
           if(isScramble(s11, s22) && isScramble(s12, s21)) return true;
       }
       return false;
    }
View Code
复制代码

其实不算难。除非你想不到递归。

posted on   lichen782  阅读(1966)  评论(1编辑  收藏  举报
< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

点击右上角即可分享
微信分享提示