您的位置:首页 > 其它

Scramble String

2014-04-03 22:57 183 查看
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.

从题目示意图可以看到,如果s1是s2的一个scramble,那必然在s1中存在一个偏移位置i把s1切分成两段 (0,i),( i + 1, s1.length() - 1)这两段,这两段的前后两种组合之一一定能和s2相对应的长度的两段形成符合scramble定义的形式。  这里i的取值范围(0, s1.length())如果I等于s1.length()则表示s1没有切分(s1直接等于s2). 

对于上边的s1的被切分出来的两段,又可以分别从头开始应用相同的分析逻辑。 

到此我们可以看出来这个问题可以分治递归解决, 但是同时注意到每层的切分都要遍历当前层所有切分位置,这样必然导致接近分治底层的基本组合情况会被多次计算,这正是动态规划要解决的问题。

最后可以得到下边的动态规划的解法,从底部开始构造,保存中间构造结果,直到把整个串都构造完毕(这时一个迭代解法,用同样的记忆法,也可以用递归来实现)。

class Solution {
public:
bool isScramble(string s1, string s2) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int len = s1.length();
if (len != s2.length()) return false;
bool ret[len][len][len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
ret[i][j][0] = (s1[i] == s2[j]);
}
}

for (int l = 2; l <= len; l++) {
for (int i = 0; i <= len - l; i++) {
for (int j = 0; j <= len - l; j++) {
ret[i][j][l - 1] = false;
for (int k = 1; k < l; k++) {
if ((ret[i][j][k - 1] && ret[i + k][j + k][l - k - 1]) ||
(ret[i][j + l - k][k - 1] && ret[i + k][j][l - k - 1])) {
ret[i][j][l - 1] = true;
break;
}
}
}
}
}

return ret[0][0][len - 1];
}

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