[leetcode] 49. Group Anagrams 解题报告

题目链接:https://leetcode.com/problems/anagrams/

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

思路:利用STL的map容器将每一个字符串排过序之后作为key,value就保存所有的具有相同字母的字符串.

然后这样遍历一遍就把所有的字符串都保存在了map中,然后对每个key所代表的集合排过序之后输出到结果数组中即可.

代码如下:

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        map> mp;
        vector> result;
        for(auto str: strs)
        {
            string tem = str;
            sort(tem.begin(), tem.end());
            mp[tem].push_back(str);
        }
        for(auto val: mp)
        {
            sort(val.second.begin(), val.second.end());
            result.push_back(val.second);
        }
        return result;
    }
};
参考:https://leetcode.com/discuss/71591/c-unordered_map-solution

你可能感兴趣的:(leetcode,hash,string,facebook)