leetcode题目 聚合相同的字母组成的单词

题目: 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.

思路: 哈希表实现

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string,int> hashmap;
        string temp;
        int pos=0;
        for(int i=0;i<strs.size();++i)
        {
            temp=strs[i];
            sort(temp.begin(),temp.end());
            if(hashmap.find(temp)==hashmap.end())
            {
                hashmap[temp]=pos++;
                result.push_back(vector<string>(1,strs[i]));
            }
            else
            {
                result[hashmap[temp]].push_back(strs[i]);
            }

        }
        for(int i=0;i<result.size();++i)
            sort(result[i].begin(),result[i].end());
        return result;
    }
};

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...