[LeetCode]87 扰乱字符串

题目描述

给定一个字符串 s1,我们可以把它递归地分割成两个非空子字符串,从而将其表示为二叉树。

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

在扰乱这个字符串的过程中,我们可以挑选任何一个非叶节点,然后交换它的两个子节点。

例如,如果我们挑选非叶节点 "gr" ,交换它的两个子节点,将会产生扰乱字符串 "rgeat"

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

我们将 "rgeat” 称作 "great" 的一个扰乱字符串。

同样地,如果我们继续将其节点 "eat""at" 进行交换,将会产生另一个新的扰乱字符串 "rgtae"

    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a

我们将 "rgtae” 称作 "great" 的一个扰乱字符串。

给出两个长度相等的字符串 s1s2,判断 s2 是否是 s1 的扰乱字符串。

示例1:

输入: s1 = "great", s2 = "rgeat"
输出: true

示例2:

输入: s1 = "abcde", s2 = "caebd"
输出: false

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
def validate(dict1, dict2):
for k in dict1:
if k not in dict2 or dict1[k]!=dict2[k]:
return False
return True

if len(s1)==1 and s1==s2:
return True
res=False
dict1=collections.defaultdict(int)
dict2=collections.defaultdict(int)
dict3=collections.defaultdict(int)
s3=s2[::-1]
i=0
while i<len(s1)-1:
dict1[s1[i]]+=1
dict2[s2[i]]+=1
dict3[s3[i]]+=1
if validate(dict1, dict2) and self.isScramble(s1[:i+1], s2[:i+1]) and self.isScramble(s1[i+1:], s2[i+1:]) or validate(dict1, dict3) and self.isScramble(s1[:i+1], s3[:i+1]) and self.isScramble(s1[i+1:], s3[i+1:]):
return True
i+=1
return False