首页 > 代码库 > [leetcode] Scramble String @python

[leetcode] Scramble String @python

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.

字符串的好题。题干解释的非常复杂,一下让人不知所措了。

这道题到底是什么意思呢?最终的结果是把一个字符串中字母的顺序打乱了,让你判断一个字符串能不能由另一个字符串打乱得到。那打乱这个过程是怎么做的呢,很简单,给你一个字符串,你必须先找一个点把它砍成两半,你可以通过交换这两半的顺序来打乱源字符串的顺序,也就是在两半中的字符与另一半中所有字符的相对顺序是统一的。对于每一半,都可以重复上面的过程。

那想一下,怎么知道打断的那个点在哪呢?穷举。怎么知道打断之后有没有做交换操作呢?两种情况递归,有一条走的通就可以了。还有个问题,两个字符串中包含的字符一定是完全一样的,怎样确定这一点呢?最暴力的方式,新开两个字符串,排序,判断这两个新的相不相等。

比如: "abcd", "bdac" are not scramble string

代码:

class Solution:    # @return a boolean    def isScramble(self, s1, s2):        if s1==s2: return True        if sorted(s1) != sorted(s2): return False  # "abcd", "bdac" are not scramble string        length=len(s1)        for i in range(1,length):            if self.isScramble(s1[:i],s2[:i])        and self.isScramble(s1[i:],s2[i:]):        return True            if self.isScramble(s1[:i],s2[length-i:]) and self.isScramble(s1[i:],s2[:length-i]): return True        return False

 

[leetcode] Scramble String @python