【题目】
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, 我们称s2是s1的scrambled string。
本题输入字符串s1和s2, 判断s2是否是s1的scrambled字符串。
【思路】
1. s1, s2长度必须相等,且拥有相同的元素,且各元素出现的次数也相同。
2. 如果s2是s1的scramble字符串,则s1一定存在一种分裂s11, s12, s2一定存在一种分裂s21,s22, 满足: isScramble(s11, s21)&&isScramble(s12, s22) || isScramble(s11, s22) && isScramble(s12, s21) 其中isScramble(x, y)表示y是x的scramble字符串。
3. 递归判断所有分裂情况。
【代码】
class Solution { public: bool isValid(string s1, string s2){ //s1和s2应该有相同种的字符,且各字符出现的次数相同 sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); if(s1.compare(s2)==0)return true; return false; } bool isScramble(string s1, string s2) { if(s1.length()!=s2.length())return false; if(s1.length()==0 || s2.length()==0)return false; if(s1.compare(s2)==0)return true; //如果s1和s2相同,则返回true; if(s1.length()==1)return false; //如果s1和s2长度为1, 且不相等,则返回false //考虑所有的分裂情况,然后递归判断 for(int len=1; len<=s1.length()-1; len++){ string s1left = s1.substr(0, len); string s1right = s1.substr(len, s1.length()-len); string s2left = s2.substr(0, len); string s2right = s2.substr(len, s1.length()-len); //在进行下一轮递归是需要先判断输入元素是否合法,如果不合法就没必要进行递归,过多的递归会使时间成本陡增 if(isValid(s1left, s2left) && isScramble(s1left, s2left) && isScramble(s1right, s2right))return true; s2left = s2.substr(0, s1.length()-len); s2right = s2.substr(s1.length()-len, len); if(isValid(s1left, s2right) && isScramble(s1left, s2right) && isScramble(s1right, s2left))return true; } return false; } };
LeetCode: Scramble String [87],布布扣,bubuko.com