您的位置:首页 > 其它

LeetCode Scramble String

2016-01-10 04:37 323 查看
Description:

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.

Solution:

dp[step][i][j]表示s1的第i个开始,s2的第j个开始,经过step步长,是否scramble

每次枚举m在[1, step)

s1中的[i, i+m), [i+m, i+len) 以及 s2中的[j, j+m), [j+m, j+len)这两个区间是否scramble

s1中的[i, i+m), [i+m, i+len) 以及 s2中的[j, j+len-m), [j+len-m, j+len)是否scramble

然后取或

区间dp的一种

<span style="font-size:18px;">public class Solution {
public boolean isScramble(String s1, String s2) {

int len1 = s1.length();
int len2 = s2.length();
int n = len1;
if (len1 != len2)
return false;

boolean dp[][][] = new boolean[n + 1]

;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (s1.charAt(i) == s2.charAt(j))
dp[1][i][j] = true;

boolean able1, able2;
for (int len = 2; len <= n; len++) {
for (int i = len1 - len; i >= 0; i--) {
for (int j = len2 - len; j >= 0; j--) {
loop: for (int m = 1; m < len; m++) {
able1 = dp[m][i][j] && dp[len - m][i + m][j + m];
able2 = dp[m][i][j + len - m]
&& dp[len - m][i + m][j];
if (able1 || able2) {
dp[len][i][j] = true;
break loop;
}
}
}
}
}

return dp
[0][0];
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: