题不难,但是开始没理解意思
用DFS就过了
枚举从哪儿断开的
有两种情况
1、正常的
2、交换了的
result = isScramble(s1.substr(0,i) , s2.substr(0,i)) && isScramble(s1.substr(i) , s2.substr(i));
这是正常的比较
result = isScramble(s1.substr(0,i) , s2.substr(s1.size()-i,i)) && isScramble(s1.substr(i) , s2.substr(0 , s1.size()-i));
这是交换了的比较
class Solution { public: bool isScramble(string s1, string s2) { //first count the characters if(s1 == s2) return true; if(s1.size() != s2.size()) return false; int charset[26] = {0}; for(int i = 0 ; i < s1.size() ; ++i) charset[s1[i]-'a']++; for(int i = 0 ; i < s2.size() ; ++i) charset[s2[i]-'a']--; for(int i = 0 ; i < 26 ; ++i) if(charset[i] != 0) return false; //end bool result = false; for(int i = 1 ; i < s1.size() ; ++i) { result = isScramble(s1.substr(0,i) , s2.substr(0,i)) && isScramble(s1.substr(i) , s2.substr(i)); if(result) return true; result = isScramble(s1.substr(0,i) , s2.substr(s1.size()-i,i)) && isScramble(s1.substr(i) , s2.substr(0 , s1.size()-i)); if(result) return true; } return false; } };
by 1957