您的位置:首页 > 其它

leetcode 49:Group Anagrams

2015-11-10 22:40 302 查看
题目:

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.

思路:
可以先对字符串进行排序,然后插入到对应的hash表里面,hash表应该是下面的形式:

unordered_map<string, vector<string>> hash;


实现如下:

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hash;
int i = 0;
for (auto s : strs)
{
sort(s.begin(), s.end());
hash[s].push_back(strs[i++]);
}
vector<vector<string>> res;
for (auto n : hash){
sort(n.second.begin(), n.second.end());
res.push_back(n.second);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: