Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
The basic idea is easy. From the definition of anagrams, we just need to get the histogram of each string. Then we just need to figure out if two string has the same histogram.
To calculate if two strings have the same histogram, we could use hashtable to do O(1) comparison, or use tree structure to do O(logN)
Now let's suppose we use the map in C++ STL to do O(logN) to compare the key. The key is actually an array of 26 numbers (each number indicate how many times a word appears in the string). To use map, we need to create a comparison method, we could do
class HistKey{
};
class MyComp{
bool operator(const HistKey &a, const HistKey &b){
//if a < b, return true;
//else return false; ********************* It is very important here that we need to return false if a==b
}
};
we could create the map by
map<HistKey, pair<string, bool>> histogram
To find if two histogram is the same for two strings, we could just do:
histogram.find(a_hist) != histogram.end()
Note, it is important that if two key are the same, it need to return false in MyComp
My code could pass the result within 240 ms. Please let me know if you would like to see the code
Reference:
Map以自定义类做为键值
http://www.seacha.com/article.php/knowledge/cbase/2011/1020/1859.html