leetcode49 - Group Anagrams - medium
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.
用map来group,最直接的办法key是一个sorted string,假设L是最长的string长度,n个string,time complexity O(nLlogL)
优化:已知都是小写字母,可以用counting sort来序列化,拼接每个字母的freq作为key,couting花的时间好于sorting,最后time complexity O(nL)
实现:
1 class Solution { 2 private: 3 string signature(string str){ 4 int counter[26] = {}; 5 for (char c : str){ 6 counter[c-'a']++; 7 } 8 string res; 9 for (int i=0; i<26; i++){ 10 res += to_string(counter[i]) + '#'; 11 } 12 return res; 13 } 14 15 public: 16 vector<vector<string>> groupAnagrams(vector<string>& strs) { 17 18 vector<vector<string>> res; 19 20 unordered_map<string, vector<string>> m; 21 for (string s : strs){ 22 string sig = signature(s); 23 m[sig].push_back(s); 24 } 25 26 for (auto row : m){ 27 res.push_back(row.second); 28 } 29 30 return res; 31 32 } 33 };
注意init counter array的时候赋个起始值

浙公网安备 33010602011771号