Scramble String
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = “great”:
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node “gr” and swap its two children, it produces a scrambled string “rgeat”.
We say that “rgeat” is a scrambled string of “great”.
Similarly, if we continue to swap the children of nodes “eat” and “at”, it produces a scrambled string “rgtae”.
We say that “rgtae” is a scrambled string of “great”.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
Example 1:
Input: s1 = “great”, s2 = “rgeat”
Output: true
Example 2:
Input: s1 = “abcde”, s2 = “caebd”
Output: false
题意
任意一个字符串都可以解析成一棵二叉树,现给出两个字符串s1和s2,判断是否存在s1的二叉树表示t1和s2的二叉树表示t2,使得t1和t2只相差一次左右子树置换
思路
动态规划。三维动态规划数组dp[i][j][k]表示存在s1[i:i+k]的二叉树表示t1和s2[j:j+k]的二叉树表示t2,使得t1和t2只相差一次左右子树置换
计算dp[i][j][k]时,l从1遍历到k-1,用l对s1[i:i+k]和s2[j:j+k]进行分割,判断分割后的字符串是否相等或互为置换
注:实际代码中为了减少dp数组大小,将上述所有k映射为k-1,所有l映射为l-1
代码
/*
* @lc app=leetcode id=87 lang=java
*
* [87] Scramble String
*/
class Solution {
public boolean isScramble(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int len = s1.length();
boolean[][][] dp = new boolean[len][len][len];
// dp[i][j][k-1] == true: s1[i:i+k] is scramble of s2[j:j+k]
for (int k=0; k<len; k++) {
for (int i=0; i+k<len; i++) {
for (int j=0; j+k<len; j++) {
if (k == 0) {
dp[i][j][k] = s1.charAt(i) == s2.charAt(j);
} else {
for (int l=0; l<k && !dp[i][j][k]; l++) {
dp[i][j][k] = dp[i][j][l] && dp[i+l+1][j+l+1][k-l-1] ||
dp[i][j+k-l][l] && dp[i+l+1][j][k-l-1];
}
}
}
}
}
return dp[0][0][len-1];
}
}