leetcode No49. Group Anagrams

来源:互联网 发布:网络机顶盒排行榜 编辑:程序博客网 时间:2024/06/15 07:14

Question:

Given an array of strings, group anagrams together.

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

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

把具有相同元素单词放一类

Algorithm:

编程珠玑2.4节有讲解:
关键问题有2个,一个是使具有相同变位词类中的单词具有相同的标识,另一个是集中具有相同标识的单词
那么解题方法就出来了:
1、排序
2、关键问题是如何把具有相同字母的单词归到一类
我们可以把单词内部排序,具有相同字母的单词则相等了
3、hash Table
map<string,vector<string>> hash;  //map->first是排序后的单词,map->second是具有相同字母的单词

Accepted Code:

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        vector<vector<string>> res;        unordered_map<string,vector<string>> hash;   //不需要用map        for(int i=0;i<strs.size();i++)        {            string s=strs[i];            sort(s.begin(),s.end());            hash[s].push_back(strs[i]);        }        unordered_map<string,vector<string>>::iterator it=hash.begin();        for(;it!=hash.end();it++)            res.push_back(it->second);        return res;    }};



0 0
原创粉丝点击