leetcode 每日一题 87. 扰乱字符串

递归

思路:

判断字符串S是否由T变换得来,可以分情况讨论:

如果S长度和T不相等,则为False;

如果S和T长度相等,那么对两个字符串进行拆分,得S1,S2 和 T1 ,T2。

那么S由T变换而来得情况有两种:

①S1 == T1 , S2 == T2

②S1 == T2 , S2 == T1

则可以将字符串递归拆分进行判断。

代码:

class Solution:
    def isScramble(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        if s1 == s2:
            return True
        if sorted(s1) != sorted(s2):
            return False

        for i in range(1, len(s1)):
            if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]) or \
                    (self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i])):
                return True
        return False

 

 

posted @ 2020-06-17 08:16  nil_f  阅读(137)  评论(0)    收藏  举报