算法描述:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
解题思路:对字符串进行排序,然后用排序后的字符串做索引建立map。
vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> results; unordered_map<string,vector<string>> map; for(int i=0; i< strs.size(); i++){ string temp = strs[i]; sort(temp.begin(),temp.end()); if(map.find(temp)==map.end()){ vector<string> strtemp; map[temp] = strtemp; } map[temp].push_back(strs[i]); } for(auto m:map){ results.push_back(m.second); } return results; }