# CCI习题1-4：Anagrams

By | 2012 年 11 月 13 日

Write a method to decide if two strings are anagrams or not.

<

pre>

//
// main.cpp
// CCI.1.4.Anagram
//
// Created by Qiu Xiangyu on 12-11-13.
//

# include

using namespace std;

bool anagram(string &str0, string &str1) {
sort(str0.begin(),str0.end());
sort(str1.begin(),str1.end());
return str0 == str1;
}

bool anagram1(string &str0, string &str1) {
if (str0.size() != str1.size()) {
return false;
}
int map[256];
for (int i = 0; i < 256; ++i)
map[i] = 0;
for (int i = 0; i < str0.size(); ++i) {
map[str0[i]] ++;
}
for (int i = 0; i < str1.size(); ++i) {
— map[str1[i]];
}
for (int i = 0; i < 256; ++i) {
if (map[i] != 0) {
return false;
}
}
return true;
}

int main(int argc, const char * argv[])
{
// insert code here…
cout << “Input Str0 below:\n”;
string str0;
cin>>str0;
cout<<“Input Str0:”<<str0<<endl<<“Input Str1 below:”<<endl;
string str1;
cin>>str1;
cout<<“Input Str1:”<<str1<<endl;

```//process
bool isAnagram = anagram1(str0,str1);
cout<<"Result : "<<isAnagram<<endl;

return 0;```

}