1 class Solution 2 { 3 public: 4 vector<vector<string>> groupAnagrams(vector<string>& strs) 5 { 6 vector<vector<string>> res; 7 if(strs.empty()) 8 return res; 9 unordered_map<string,vector<string>> svmap; 10 for(string &s : strs) 11 svmap[sortstring(s)].push_back(s); 12 for(auto p : svmap) 13 res.push_back(p.second); 14 return res; 15 } 16 17 string sortstring(string & st) 18 { 19 string t=st; 20 sort(t.begin(),t.end()); 21 return t; 22 } 23 };
这里利用了乱序序列排序后是相等的这一点,把所有字符串排序,然后用map来添加至容器,很机智
浙公网安备 33010602011771号