---
# System prepended metadata

title: Group Anagrams
tags: [Medium, Hash_table]

---

# Group Anagrams

###### tags: `Medium`、`Hash_table`

https://leetcode.com/problems/group-anagrams/submissions/
![](https://i.imgur.com/5VZyEyi.png)

- 大神的寫法
```cpp=
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, int> htable;
        vector<vector<string>> result; int next_index = 0;
        
        for(int i = 0; i < strs.size(); ++i) {
            
            auto str = strs[i]; int cur_index = -1;
            sort(str.begin(), str.end());
            
            if(htable.find(str) == htable.end()) {
                htable[str] = next_index;
                result.emplace_back(vector<string>());
                next_index++;
            }
            
            cur_index = htable[str];
            result[cur_index].push_back(strs[i]);
        }
        
        return result;
    }
};
```
