本文共 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/