Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
AC code:
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> mp; vector<vector<string>> res; for (auto str : strs) { string tage = str; sort(tage.begin(), tage.end()); mp[tage].push_back(str); } for (auto m : mp) { sort(m.second.begin(), m.second.end()); res.push_back(m.second); } return res; } };
Runtime: 36 ms, faster than 37.09% of C++ online submissions for Group Anagrams.