本文主要是介绍leetcode 87 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.
分析:
一个字符串有很多种二叉表示法,解决复杂问题的方法是从简单的特例来思考,从而找出规律。
先考察简单情况:
字符串长度为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<s1.length();i++){bool result=(isScramble(s1.substr(0,i),s2.substr(0,i))&&isScramble(s1.substr(i),s2.substr(i)))||(isScramble(s1.substr(0,i),s2.substr(s2.length()-i,i))&&isScramble(s1.substr(i),s2.substr(0,s2.length()-i)));if(result)return true;}return false;}
};
python代码:
class Solution(object):def isScramble(self, s1, s2):""":type s1: str:type s2: str:rtype: bool"""if s1==s2:return Truel1=sorted(s1)#返回一个列表l2=sorted(s2)if l1!=l2:return Falsefor 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 Truereturn False
友情链接:
关于Python切片,请参考: python切片操作
关于sorted函数的使用,请参考: python sorted()函数这篇关于leetcode 87 Scramble String(递归+剪枝)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!