首页 > 其他 > 详细

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

时间:2020-06-17 10:20:31      阅读:62      评论:0      收藏:0      [点我收藏+]

技术分享图片

技术分享图片

递归

思路:

判断字符串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

 

 

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

原文:https://www.cnblogs.com/nilhxzcode/p/13150357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!