• 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

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

  • 相关阅读:
    webgame模块划分
    VC的若干实用小技巧(一)
    反病毒技术:从亡羊补牢到免疫防御
    MySQL 备份和恢复
    企业网络安全整体解决方案
    大型银行核心网络的三层结构设计
    编写"优美"的SHELLCODE
    linux中apache访问控制配置文件。
    网站同步镜像制作!
    Linux远程桌面(vnc)
  • 原文地址:https://www.cnblogs.com/lichen782/p/leetcode_Scramble_String.html
Copyright © 2020-2023  润新知