凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 49. Group Anagrams

分类:algorithm| 发布时间:2016-10-14 11:05:00


题目

Given an array of strings, group anagrams together.

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

Return:

[
    ["ate", "eat","tea"],
    ["nat","tan"],
    ["bat"]
]

Note: All inputs will be in lower-case.

题意

给出一组字符串,将其分组。

解法

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> m;
        for (string &s: strs) {
            string tmp = s;
            sort(tmp.begin(), tmp.end());
            m[tmp].push_back(s);
        }

        vector<vector<string>> ret;
        for (auto i = m.begin(); i != m.end(); ++i) {
            ret.push_back(i->second);
        }

        return ret;
    }
};