要求
给定三个字符串 s1、s2、s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。
两个字符串 s 和 t 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串:
- s = s1 + s2 + ... + sn
- t = t1 + t2 + ... + tm
- |n - m| <= 1
- 交错 是 s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ... 提示:a + b 意味着字符串 a 和 b 连接。
示例 1:
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出:true
示例 2:
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出:false
示例 3:
输入:s1 = "", s2 = "", s3 = ""
输出:true
提示:
- 0 <= s1.length, s2.length <= 100
- 0 <= s3.length <= 200
- s1、s2、和 s3 都由小写英文字母组成
核心代码
cache = dict()
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
if not s1:
return s2 == s3
if not s2:
return s1 == s3
key = (s1,s2,s3)
if key not in cache:
if s1[0] != s3[0] and s2[0] != s3[0]:
cache[key] = False
elif s1[0] != s3[0]:
cache[key] = self.isInterleave(s1,s2[1:],s3[1:])
elif s2[0] != s3[0]:
cache[key] = self.isInterleave(s1[1:],s2,s3[1:])
else:
cache[key] = self.isInterleave(s1[1:],s2,s3[1:]) or self.isInterleave(s1,s2[1:],s3[1:])
return cache[key]
解题思路:我们使用递归的方式进行处理,当s3字符串的头和s1或s2都不同的时候,我们直接判定非交换字符串,当有有一个字符相同的时候我们,我们直接减去一个字符,然后进行递归操作,找到递归的位置即可。