给定一个字符串 s1,我们可以把它递归地分割成两个非空子字符串,从而将其表示为二叉树。
示例 1:
输入: s1 = "great", s2 = "rgeat" 输出: true
示例 2:
输入: s1 = "abcde", s2 = "caebd" 输出: false
解答:本题可以用递归算法来处理。递归函数的逻辑如下:
【1】对字符串进行排序,比较排序后字符串是否相等
【2】对字符串进行切割,判断正对比是否符合要求(递归);判断反对比是否符合要求(递归);
【3】若否,返回false;
//87 bool isScramble(string s1, string s2) { if(s1 == s2) return true; if(s1.size()!=s2.size()) return false; string str1 = s1, str2 = s2; sort(str1.begin(),str1.end()); sort(str2.begin(),str2.end()); if(str1 != str2) return false; for(int i=1;i<(signed)s1.size();i++) { string s11 = s1.substr(0,i); string s12 = s1.substr(i); string s21 = s2.substr(0,i); string s22 = s2.substr(i); if(isScramble(s11,s21) && isScramble(s12,s22)) return true; s21 = s2.substr(s2.size()-i,i); s22 = s2.substr(0,s2.size()-i); if(isScramble(s11,s21) && isScramble(s12,s22)) return true; } return false; }//87