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.
Solution: HashTable
The sorted word will be the key of each group
Time complexity: O(sum(l*log(l)))
Space complexity: O(sum(l))
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> ans; unordered_map<string, vector<int>> m; for (int i = 0; i < strs.size(); ++i) { string c = strs[i]; sort(begin(c), end(c)); m[c].push_back(i); } for (const auto& kv : m) { ans.push_back({}); for (int i : kv.second) ans.back().push_back(strs[i]); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment