[leetcode] 49.Group Anagrams

来源:互联网 发布:企查查数据接口 编辑:程序博客网 时间:2024/05/02 00:35

题目:
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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.
题意:
给定一堆字符串,寻找每个分组,每个分组的字符串拥有相同的字符,并且分组里的元素需要按照字典排序。
思路:
首先对于原始字符串们,我们进行字典排序,直接调用STL的sort函数即可。然后我们知道同一组的字符串如果按照字符进行重新排序,那么应该是一样的。所以我们使用unordered_map这个基于hash 的map,里面的value存放的是应该将该字符串存入的vector数组的下标。
以上。
代码如下:

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        vector<vector<string>> result;        if(strs.empty())return result;        sort(strs.begin(), strs.end());        unordered_map<string, int> table;        int count = 0;        for(auto str:strs) {            auto temp = str;            sort(temp.begin(), temp.end());            if(table.find(temp) == table.end()) {                table.insert(pair<string,int>(temp, count));                result.push_back(vector<string>(1, str));                count++;            }            else {                result[table[temp]].push_back(str);            }        }        return result;    }};
0 0