博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 87 Scramble String(递归+剪枝)
阅读量:4170 次
发布时间:2019-05-26

本文共 2536 字,大约阅读时间需要 8 分钟。

题目描述:
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.

分析:

一个字符串有很多种二叉表示法,解决复杂问题的方法是从简单的特例来思考,从而找出规律。
先考察简单情况:
字符串长度为1:很明显,两个字符串必须完全相同才可以。
字符串长度为2:当s1="ab", s2只有"ab"或者"ba"才可以。
对于任意长度大于2的字符串,我们可以把字符串s1分为非空的 left1 和 right1 两个部分,s2分为非空的 left2 ,right2 两个部分,
满足((left1,left2) && (right1,right2))或者 ((left1,right2) && (right1,left2))
即:我们需要考虑下面几种情况:
1.如果两个substring相等的话,则为true
2.如果两个substring长度不等,则为false
3.如果两个substring排序后不相等,则为false
4.如果两个substring中间某一个点,左边的substrings为scramble string,同时右边的substrings也为scramble string,则为true
5.如果两个substring中间某一个点,s1左边的substring和s2右边的substring为scramblestring, 同时s1右边substring和s2左边的substring也为scramble string,则为true
容易想到的方法:递归+剪枝:
两个字符串的满足题意的必备条件是含有相同的字符集。
简单的做法是把两个字符串的字符排序后,然后比较是否相同,如不相同,直接返回False。通过这样的检查来剪枝,就可以大大的减少递归次数。

C++代码:

class Solution {public:    bool isScramble(string s1, string s2) {        if(s1==s2)return true;        if(s1.length()!=s2.length())return false;//剪枝,若满足题意,长度肯定相等        string s11=s1;//生成s1和s2的副本,以便排序。(不要对s1和s2进行排序)        string s22=s2;        sort(s11.begin(),s11.end());        sort(s22.begin(),s22.end());        if(s11!=s22)return false;//剪枝,若满足题意,排序后,二者一定相等。        for(int i=1;i

python代码:

class Solution(object):    def isScramble(self, s1, s2):        """        :type s1: str        :type s2: str        :rtype: bool        """        if s1==s2:            return True        l1=sorted(s1)#返回一个列表        l2=sorted(s2)        if l1!=l2:            return False        for i in range(1,len(s1)):            result=(self.isScramble(s1[:i],s2[0:i:1]) and self.isScramble(s1[i:],s2[i::1]))            result=result or (self.isScramble(s1[:i],s2[len(s2)-i::1]) and self.isScramble(s1[i::1],s2[:len(s2)-i]))            if result==True:                return True        return False

友情链接:

关于Python切片,请参考:

关于sorted函数的使用,请参考:

转载地址:http://ucyai.baihongyu.com/

你可能感兴趣的文章
Yocto tips (4): Yocto 如何确定(找到)一个包的名字
查看>>
start kernel 之后没有任何输出与uboot无法将bootargs传入内核的调查方法与解决之道
查看>>
Yocto tips (5): Yocto如何更改source code的下载与git clone地址
查看>>
Yocto tips (7): Yocto Bitbake的clean与cleanall以及cleansstate的区别
查看>>
Yocto tips (19): Yocto SDK Toolchian的使用
查看>>
Yocto i.MX6 (TQIMX6) (04) : 使用mjpg-streamer做一个WebCam Server
查看>>
Nexus 7 Cyanogenmod OS Compile and errors
查看>>
Yocto tips (20): Yocto中qemu模拟器的使用,以zynq Cortex-A9为例
查看>>
打造嵌入式ARM Linux防火墙:1. iptables基础
查看>>
4G模块SIMCOM7100 LTE在ARM Linux下使用PPPD上网
查看>>
为小米4与小米3 Mi3 Mi4编译Cyanogenmod 12.1与13.0 (CM12与CM13) 的步骤以及错误解决
查看>>
原生Android系统的第一次开机google验证的解决
查看>>
S5P4418与S5P6618的Android boot.img的解压与压缩, Sparse ext4文件系统
查看>>
【EVB-335X-II试用体验】 u-boot与kernel的编译以及本地repo的建立
查看>>
【EVB-335X-II试用体验】 上手试用与资源使用
查看>>
【EVB-335X-II试用体验】 Yocto环境的建立及Rootfs的构建与使用
查看>>
<<C++程序设计原理与实践>>粗读--chapter0 chapter1 chapter2
查看>>
<<C++程序设计原理与实践>>粗读--chapter3 chapter4 Chapter5
查看>>
<<C++程序设计原理与实践>>粗读 -- chapter8 Chapter9
查看>>
Linux Qt程序打包成一个可执行文件
查看>>