Hard
We can scramble a string s to get a string t using the following algorithm:
s
, divide it to x
and y
where s = x + y
.s
may become s = x + y
or s = y + x
.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
.
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
and s2
consist of lower-case English letters.public class Solution {
public boolean isScramble(String s1, String s2) {
int n = s1.length();
boolean[][][] dp = new boolean[n][n][n + 1];
for (int len = 1; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
for (int j = 0; j <= n - len; j++) {
if (len == 1) {
dp[i][j][len] = s1.charAt(i) == s2.charAt(j);
} else {
for (int k = 1; k < len && !dp[i][j][len]; k++) {
dp[i][j][len] =
(dp[i][j][k] && dp[i + k][j + k][len - k])
|| (dp[i][j + len - k][k] && dp[i + k][j][len - k]);
}
}
}
}
}
return dp[0][0][n];
}
}