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
1:采用递归;2:注意递归结束条件;3:特殊情况进行处理;
bool isScramble(string s1, string s2)
{
if(s1.size() != s2.size())
{
return false;
}
if(strcmp(s1.c_str(), s2.c_str()) == 0)
{
return true;
}
int A[256] = {0};
for(int i = 0; s1[i] != '\0' ; i++)
{
A[s1[i]]++;
}
for(int i = 0; s2[i] != '\0'; i++)
{
A[s2[i]]--;
}
for(int i = 0; i < 256; i++)
{
if(A[i] != 0)
{
return false;
}
}
bool flag = false;
int size = (int)s1.size();
for(int i = 1; i < size; i++)
{
flag = isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i, size - i), s2.substr(i, size - i));
if(flag == false)
{
flag = isScramble(s1.substr(0, i), s2.substr(size - i, i)) && isScramble(s1.substr(i, size - i), s2.substr(0, size - i));
}
if(flag)
{
break;
}
}
return flag;
}

本文介绍了一种判断两个字符串是否可以通过特定规则相互转换的算法。该算法通过递归方式检查字符串能否通过子串交换的方式相互转换,并确保了即使在字符串进行多次内部节点交换后仍能正确判断。
403

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



