LeetCode 0049 - Group Anagrams

2021-08-11 10:39:00 浏览数 (1)

Group Anagrams

Desicription

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:

代码语言:javascript复制
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

Solution

代码语言:javascript复制
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        sort(strs.begin(), strs.end());
        map<string, vector<string>> mp;
        int len = strs.size();
        for(int i = 0; i < len; i  ){
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            mp[tmp].push_back(strs[i]);
        }
        vector<vector<string>> res;
        for(auto it = mp.begin(); it != mp.end(); it  )
            res.push_back(it->second);
        return res;
    }
};

0 人点赞