扰乱字符串
成两个子字符串×和 y ,且满足 s = X + y 。
●随机决定是要「交换两个子字符串还是要「保持这两个子字符串的顺序不变。即,在执行这一步骤之后, s 可能是 s = X + y 或者 s = y + X 。
●在×和 y 这两个子字符串上继续从步骤1开始递归执行此算法。
给你两个长度相等的字符串s1和s2,判断s2是否是 S1的扰乱字符串。如果是,返回 true ;否则,返回 false 。
示例1:
输入:s1=" great ",s2=" rgeat "
输出: true
示例2:
输入:s1=" abcde ",s2=" caebd "
输出: false
class Soulution:
def isScramble(self, s1, s2, memo={}):
if len(s1) != len(s2) or sorted(s1) != sorted(s2): return False
if len(s1) <= len(s2) <= 1: return s1 == s2
if s1 == s2: return True
if (s1, s2) in memo:
return memo[s1, s2]
n = len(s1)
for i in range(1, n):
a = self.isScramble(s1[:i], s2[:i], memo) and self.isScramble(s1[i:], s2[i:], memo)
if not a:
b = self.isScramble(s1[:i], s2[-i:], memo) and self.isScramble(s1[i:], s2[:-i], memo)
if a or b:
memo[s1, s2] = True
return True
memo[s1, s2] = False
return False
print(Soulution().isScramble(s1='great', s2='rgeat'))
扰乱字符串成两个子字符串×和 y ,且满足 s = X + y 。●随机决定是要「交换两个子字符串还是要「保持这两个子字符串的顺序不变。即,在执行这一步骤之后, s 可能是 s = X + y 或者 s = y + X 。●在×和 y 这两个子字符串上继续从步骤1开始递归执行此算法。给你两个长度相等的字符串s1和s2,判断s2是否是 S 1的扰乱字符串。如果是,返回 true ;否则,返回 fal se 。示例1:输入:s1=" great ",s2=" rgeat "输出: tru.