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 tox
andy
wheres = x + y
. - Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
s
may becomes = x + y
ors = y + x
. - Apply step 1 recursively on each of the two substrings
x
andy
.
- Split the string into two non-empty substrings at a random index, i.e., if the string is
Given two strings s1
and s2
of the same length, return true
if s2
is a scrambled string of s1
, otherwise, return false
.
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
Constraints:
s1.length == s2.length
1 <= s1.length <= 30
s1
ands2
consist of lower-case English letters.
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
n = len(s1)
dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
dp[i][j][1] = s1[i] == s2[j]
for l in range(2, n + 1):
for i1 in range(n - l + 1):
for i2 in range(n - l + 1):
for i in range(1, l):
if dp[i1][i2][i] and dp[i1 + i][i2 + i][l - i]:
dp[i1][i2][l] = True
break
if dp[i1][i2 + l - i][i] and dp[i1 + i][i2][l - i]:
dp[i1][i2][l] = True
break
return dp[0][0][n]
class Solution {
public boolean isScramble(String s1, String s2) {
int n = s1.length();
boolean[][][] dp = new boolean[n][n][n + 1];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
dp[i][j][1] = s1.charAt(i) == s2.charAt(j);
}
}
for (int len = 2; len <= n; ++len) {
for (int i1 = 0; i1 <= n - len; ++i1) {
for (int i2 = 0; i2 <= n - len; ++i2) {
for (int i = 1; i < len; ++i) {
if (dp[i1][i2][i] && dp[i1 + i][i2 + i][len - i]) {
dp[i1][i2][len] = true;
break;
}
if (dp[i1][i2 + len - i][i] && dp[i1 + i][i2][len - i]) {
dp[i1][i2][len] = true;
break;
}
}
}
}
}
return dp[0][0][n];
}
}