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.
思路解析:
1、先将向量中的字符串按字典排序(因为必须按字典的顺序,因此先排序)
也就是[ate, bat, eat, nat, tan, tea]
2、将向量中的每个字符串排序,并且将其中字典序最小的作为map中的键值
aet -> ate,eat,tea
bat -> bat,
ant->nat,tan
/* */ #include "stdafx.h" #include <iostream> #include <algorithm> #include <vector> #include <map> using namespace std; class Solution_049_GroupAnagrams { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { if (strs.empty()) { return vector<vector<string> >(); } int len = strs.size(); //将字符串数组按照字典顺序排列 sort(strs.begin(), strs.end()); vector<vector<string> > ret; //利用哈希思想构建map,将排序后相等的字符串存在相应的vector map<string, vector<string> > mv; for (int i = 0; i < len; i++) { string str = strs[i]; sort(str.begin(), str.end()); //每个相同的str都有一个向量与之对应 mv[str].push_back(strs[i]); } for (map<string, vector<string>>::iterator iter = mv.begin(); iter != mv.end(); iter++) { ret.push_back(iter->second); } return ret; } };