49. Group Anagrams
时间:2017-06-14 20:05:15
收藏:0
阅读:268
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: All inputs will be in lower-case.
很明显,这个题目要求将字母相同的单词归为一组。
判断字符串中字符相同一般有两种方法:
- 使用容器map<char, int>
- 排序,然后使用=运算符判断是否相等
具体到本题中,可以将字符串排序后的结果作为key,vector<string>作为value,使用map<key, vector<string>>,每个key对应的vector<string>就是同一组单词。
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; if (strs.empty()) return res; unordered_map<string, vector<string>> container; for (auto str : strs) { string tmp(str); std::sort(tmp.begin(), tmp.end()); (container[tmp]).push_back(str); } for (auto ele : container) res.push_back(ele.second); return res; } };
原文:http://www.cnblogs.com/naivecoder/p/7010611.html
评论(0)