leetcode题目 聚合相同的字母组成的单词
发布时间:2020-12-13 22:14:00 所属栏目:百科 来源:网络整理
导读:题目: 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 lis
题目: Given an array of strings,group anagrams together. For example,given: [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”], 1.For the return value,each inner list’s elements must follow the lexicographic order. 思路: 哈希表实现 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;
}
};
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |