Anagrams

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

C++:
01 bool anagram(string a, string b)
02 {
03     int len=a.size();
04     if(b.size()!=len)
05         return false;
06     map <char, int> m;
07     for(int i=0;i<len;i++){
08         char t=a.at(i);
09         if(m.find(t)==m.end())
10             m.insert(pair<char, int>(t,1));
11         else
12             m[t]++;
13     }
14     for(int i=0;i<len;i++){
15         char t=b.at(i);
16         if(m.find(t)==m.end())
17             return false;
18         else
19             m[t];
20         if(m[t]==0)
21             m.erase(t);
22     }
23     return true;
24 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s