Group Anagrams
My Submissions
Question
Total Accepted: 54426 Total Submissions: 217518 Difficulty: Medium
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.
Subscribe to see which companies asked this question
觉得还是应该锻炼一下代码能力,这几天一直看课件,找知识,动手能力确实下降。
1 class Solution { 2 public: 3 vector<vector<string>> groupAnagrams(vector<string>& strs) { 4 vector<vector<string>> result; 5 std:sort(strs.begin(),strs.end()); 6 map<string,vector<string>> strtoarray; 7 int i; 8 for(i=0;i<strs.size();i++){ 9 strtoarray[tostr(strs[i])].push_back(strs[i]); 10 } 11 map<string,vector<string>>::iterator it; 12 for(it=strtoarray.begin();it!=strtoarray.end();it++){ 13 result.push_back(it->second); 14 } 15 return result; 16 } 17 18 19 string tostr(string str){ 20 std:sort(str.begin(),str.end()); 21 return str; 22 } 23 };