1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class Solution { private: map<string,int> m; public: bool isScramble(string s1, string s2) { map<string,int>::iterator iter; iter=m.find(s1+'#'+s2); if(iter!=m.end()) { if(iter->second==0) return false; else if(iter->second==1) return true; } if(s1.length()!=s2.length()) { m.insert(pair<string,int>(s1+'#'+s2,0)); return false; } if(s1==s2) { m.insert(pair<string,int>(s1+'#'+s2,1)); return true; } int f[26]={0}; int i,a,b; for(i=0;i<s1.length();i++) { a=s1[i]-'a'; b=s2[i]-'a'; f[a]++; f[b]--; } for(i=0;i<26;i++) { if(f[i]!=0) { m.insert(pair<string,int>(s1+'#'+s2,0)); return false; } } for(i=1;i<s1.length();i++) { if(isScramble(s1.substr(0,i),s2.substr(0,i))&&isScramble(s1.substr(i,s1.length()),s2.substr(i,s2.length()))) { m.insert(pair<string,int>(s1+'#'+s2,1)); return true; } if(isScramble(s1.substr(0,i),s2.substr(s2.length()-i,i))&&isScramble(s1.substr(i,s1.length()),s2.substr(0,s2.length()-i))) { m.insert(pair<string,int>(s1+'#'+s2,1)); return true; } } m.insert(pair<string,int>(s1+'#'+s2,0)); return false; } };
|