标签:
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":
great
/ gr eat
/ \ / g r e at
/ a t
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".
rgeat
/ rg eat
/ \ / r g e at
/ a t
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".
rgtae
/ rg tae
/ \ / r g ta e
/ t a
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.
题意:求s2是否是s1的拆分串。思路:一种是递归搜索,每次都是把一个串分成长度为i和len-i的两个穿,再交叉比较;第二种是DP,设dp[len][i][j]表示的是s1第i个位置开始的长度为len的s2第j个位置开始的长度为len的是否满足条件。
public class Solution {
public boolean isScramble(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 != len2) return false;
if (len1 == 1) return s1.equals(s2);
char str1[] = s1.toCharArray();
char str2[] = s2.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
if (Arrays.equals(str1, str2) == false) return false;
for (int i = 1; i < len1; i++) {
String s11 = s1.substring(0, i);
String s12 = s1.substring(i, len1);
String s21 = s2.substring(0, i);
String s22 = s2.substring(i, len1);
if (isScramble(s11, s21) && isScramble(s12, s22)) return true;
s21 = s2.substring(0, len1-i);
s22 = s2.substring(len1-i, len1);
if (isScramble(s11, s22) && isScramble(s12, s21)) return true;
}
return false;
}
}public class Solution {
public boolean isScramble(String s1, String s2) {
int len = s1.length();
if (len != s2.length()) return false;
if (len == 0) return false;
char c1[] = s1.toCharArray();
char c2[] = s2.toCharArray();
boolean dp[][][] = new boolean[len+1][len+1][len+1];
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++)
dp[1][i][j] = c1[i] == c2[j];
for (int k = 2; k <= len; k++)
for (int i = len-k; i >= 0; i--)
for (int j = len-k; j >= 0; j--) {
boolean flag = false;
for (int m = 1; m <= k && !flag; m++) {
flag = (dp[m][i][j] && dp[k-m][i+m][j+m]) ||
(dp[m][i][j+k-m] && dp[k-m][i+m][j]);
}
dp[k][i][j] = flag;
}
return dp[len][0][0];
}
}标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45028881