Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Thoughts:
What is the definition of anagrams?
One thing has to be thought over: do "" and "" together make a pair of anagrams?
After we defined anagrams, the algorithm straight in the mind is hash. What is a good hash algorithm? There are several possibilities. Two of them are: 1. hash by sorting the string; 2. hash by counting the number of used characters, respectively. The latter is used in the solution.
Solution:
- class Solution {
- public:
- struct StringHash
- {
- char hash[26];
- StringHash(const string& str)
- {
- fill(hash, hash+26, 0);
- for(auto& ch : str)
- ++ hash[ch - 'a'];
- }
- bool operator<(const StringHash& sh) const
- {
- for(size_t i = 0; i < 26; ++i)
- if ( this->hash[i] < sh.hash[i] )
- return true;
- else if ( this->hash[i] > sh.hash[i] )
- return false;
- return false;
- }
- };
- vector<string> anagrams(vector<string> &strs)
- {
- map<StringHash, vector<vector<string>::iterator>> hash_map;
- for(auto iter=begin(strs); iter != end(strs); ++iter)
- hash_map[StringHash(*iter)].push_back(iter);
- vector<string> ret;
- for(auto hsm : hash_map)
- if (hsm.second.size() >= 2)
- for(auto i : hsm.second)
- ret.push_back(*i);
- return ret;
- }
No comments:
Post a Comment