您的位置:首页 > 编程语言 > Python开发

LeetCode 87 Scramble String (Python详解及实现)

2017-08-09 18:30 731 查看
【题目】

Given a string s1, we may represent it as abinary 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 anynon-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 ascrambled string of "great".

 

Similarly, if we continue to swap thechildren of nodes "eat" and "at", it produces a scrambledstring "rgtae".

 

   rgtae

  /    \

 rg    tae

 /\    / \

r  g  ta  e

      / \

     t   a

We say that "rgtae" is ascrambled string of "great".

 

Given two strings s1 and s2 of the samelength, determine if s2 is a scrambled string of s1.

 

首先解释一下scramble:给定一个字符串,字符串展成一个二叉树,如果二叉树某个或多个左右子树颠倒得到新的字符串,这就是所谓得scramble。本题要做的是给定两个字符串,判断是否互为scramble。

【思路】

可以使用递归。

 

【Python实现】

class Solution(object):
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s1) != len(s2):
return False
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
sl_len = len(s1)
f = self.isScramble
for i in range(1, sl_len):
if f(s1[i:], s2[i:]) and f(s1[:i], s2[:i]):
return True
if f(s1[i:], s2[:sl_len - i]) and f(s1[:i], s2[sl_len - i:]):
return True
return False

            

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Python