Home LeetCode - 49. Group Anagrams
Post
Cancel

LeetCode - 49. Group Anagrams

49. Group Anagrams - medium

문제

Given an array of strings, group anagrams together.

제한사항

  • All inputs will be in lowercase.
  • The order of your output does not matter.

입출력 예

1
2
3
4
5
6
7
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

풀이

  • Hash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
bool compare(vector<string> a, vector<string> b){
        return a.size() < b.size();
}

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string, vector<string>> item;
        
        for(auto i = 0 ; i < strs.size() ; ++i){
            string copy = strs[i];
            
            sort(strs[i].begin(), strs[i].end());
            item[strs[i]].push_back(copy);
        }
        
        for(auto &i : item){
            vector<string> sub;
        
            for(auto j = 0 ; j < i.second.size() ; ++j)
                sub.push_back(i.second[j]);
                
            result.push_back(sub);
        }
        
        return result;
    }
};
This post is licensed under CC BY 4.0 by the author.