LeetCode [Hash Table]: Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Idea: Sort all the letters of each word in alphabetical order, and sort the results as keys. All words with the same key are combined into an anw.group. Finally, all anetag groups are returned.
class Solution {public: vector
anagrams(vector
&strs) { vector
result; unordered_map
> dict; for (auto word : strs) dict[getLetters(word)].push_back(word); for (auto wordGroup : dict) if (wordGroup.second.size() > 1) result.insert(result.end(), wordGroup.second.begin(), wordGroup.second.end()); return result; }private: string getLetters(string word) { string letters; for (auto letter : word) { int i; for (i = 0; i < letters.size(); ++i) if (letters[i] > letter) break; letters.insert(letters.begin() + i, letter); } return letters; }};
In the above solution, the insertion sorting algorithm written by myself is used for sorting each word in alphabetical order, or the sort function can be used.
class Solution {public: vector
anagrams(vector
&strs) { vector
result; unordered_map
> dict; for (auto word : strs){ string tmp = word; sort(tmp.begin(), tmp.end()); dict[tmp].push_back(word); } for (auto group : dict) if (group.second.size() > 1) result.insert(result.end(), group.second.begin(), group.second.end()); return result; }};