Description
We can scramble a string s to get a string t using the following algorithm:
- If the length of the string is 1, stop.
- If the length of the string is > 1, do the following:
• Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.
• Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
• Apply step 1 recursively on each of the two substrings x and y.
Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
Constraints:
• s1.length == s2.length
• 1 <= s1.length <= 30
• s1 and s2 consist of lower-case English letters.
Example
Example 1:
Input: s1 = “great”, s2 = “rgeat”
Output: true
Explanation: One possible scenario applied on s1 is:
“great” --> “gr/eat” // divide at random index.
“gr/eat” --> “gr/eat” // random decision is not to swap the two substrings and keep them in order.
“gr/eat” --> “g/r / e/at” // apply the same algorithm recursively on both substrings. divide at ranom index each of them.
“g/r / e/at” --> “r/g / e/at” // random decision was to swap the first substring and to keep the second substring in the same order.
“r/g / e/at” --> “r/g / e/ a/t” // again apply the algorithm recursively, divide “at” to “a/t”.
“r/g / e/ a/t” --> “r/g / e/ a/t” // random decision is to keep both substrings in the same order.
The algorithm stops now and the result string is “rgeat” which is s2.
As there is one possible scenario that led s1 to be scrambled to s2, we return true.
Example 2:
Input: s1 = “abcde”, s2 = “caebd”
Output: false
Example 3:
Input: s1 = “a”, s2 = “a”
Output: true
Submissions
解题思路该题可以通过memory + dfs来解决,换句话说,是动态编程。我们memo用来存储已知的子问题,并利用dfs(s1, s2)递归地解决问题。
对于递归函数,我们先找出可以直接返回答案的简单情况,再考虑复杂情况。
- 对s1和s2进行排序,如果s1 != s2则返回false,说明s1和s2中字母不匹配。
- 对s1和s2进行排序,如果s1 == s2,则返回true。
- 递归尝试所有可能的位置进行调换。
• 假设s1在第i处分割成了两个字符串s1[:i]和s1[i:],s2也在第i处分割成了两个字符串s2[:i]和s2[i:],只要s1[:i]能够通过交换成为s2[:i],s1[i:]也能够通过交换成为s2[i:],那么s2便是s1的扰乱字符串。
• 或者s1本身在i处进行交换,如果s1[i:]能够通过交换成为s2[:i],s1[:i]也能够通过交换成为s2[i:],那么s2也是s1的扰乱字符串。
注:对于i值的探索,尝试每一个可能的位置,一旦找到True情况,即可直接break并返回True。
实现代码如下:
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
memo = {}
def dfs(s1, s2):
if (s1, s2) not in memo:
if sorted(s1) != sorted(s2):
flag = False
elif s1 == s2:
flag = True
else:
for i in range(1, len(s1)):
flag = (dfs(s1[:i], s2[:i]) and dfs(s1[i:], s2[i:])) \
or (dfs(s1[:i], s2[-i:]) and dfs(s1[i:], s2[:-i]))
if flag:
break
memo[s1,s2] = flag
return memo[s1,s2]
return dfs(s1, s2)