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.
» Solve this problem
枚举分割点,判断左右是否相同,是最自然的解法:
for (int i = 0; i < length; i++) {
if ((isEqual(S1[0..i], S2[0..i]) && isEqual(S1[i + 1 .. length - 1], S2[i + 1 .. length - 1]) || (isEqual(S1[0..i], S2[l - 1 - i..i) && isEqual(S1[i + 1.. length-1], S2[0..l - i - 2])) {
return true;
}
}
return false;isEqual采用递归实现。
还存在更高效的算法:动态规划。
定义F[i][j][k],
当F[i][j][k]=true时,表示S1[i..i+k-1] == S2[j..j+k-1]。
用白话表达:F[i][j][k]记录的是S1从i开始k个字符与S2从j开始k个字符是否为Scramble String。
最简单的情况为k=1时,即S1[i]与S2[j]是否为Scramble String。
因此F[i][j][1] = S1[i] == S2[j]。
当K=2时,
F[i][j][2] = (F[i][j][1] && F[i+1][j+1][1]) || (F[i][j+1][1] && F[i+1][j][1])。
F[i][j][1] && F[i+1][j+1][1]表达的是 S1[i] == S2[j] && S1[i+1]==S2[j+1](例如:“AC”和“AC”),如果这个条件满足,那么S1[i..i+1]与S2[j..j+1]自然为Scramble String,即F[i][j][2] = true。
F[i][j+1][1] && F[i+1][j][1]表达的是S1[i+1] == S2[j] && S1[i] == S2[j + 1] (例如: “AB”和“BA”),同样如果该条件满足,F[i][j][2] = true。
当K为更大的数时,同递归算法一样,我们需要枚举分割点,假设左边长度为l,即S[i..i+l-1],右边长度为k-l,即S[i+l..i+k-1]。
同样存在两种情况,S1左 = S2左 && S1右 = S2右 或者 S1左 = S2右 && S1右 = S2左。
class Solution {
public:
bool isScramble(string s1, string s2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s1.length() != s2.length()) {
return false;
}
int length = s1.length();
bool f[length][length][length];
memset(f, false, sizeof(bool) * length * length * length);
for (int k = 1; k <= length; k++) {
for (int i = 0; i <= length - k; i++) {
for (int j = 0; j <= length - k; j++) {
if (k == 1) {
f[i][j][k] = s1[i] == s2[j];
}
else {
for (int l = 1; l < k; l++) {
if ((f[i][j][l] && f[i + l][j + l][k - l]) || (f[i][j + k - l][l] && f[i + l][j][k - l])) {
f[i][j][k] = true;
break;
}
}
}
}
}
}
return f[0][0][length];
}
};
本文介绍了一种判断两个等长字符串是否可通过特定规则相互转换的算法。通过递归和动态规划的方法,解决字符串乱序匹配问题,即判断一个字符串是否为另一个字符串的乱序版本。
1730

被折叠的 条评论
为什么被折叠?



