还是先排序,看排完序后的字符串是否一致,如果一致,就把他们归为一类。
刚学java,对比一下两种写法,java确实简单一些。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
int len=strs.length;
Map<String, List<String>> res;
res=new HashMap<String,List<String>>();
int i=0;
String s;
while(i<len){
s=strs[i];
char[] arr=s.toCharArray();
Arrays.sort(arr);
String key=new String(arr);
List<String> list = res.getOrDefault(key,new ArrayList<String>());
list.add(s);
res.put(key,list);
i++;
}
return new ArrayList<List<String>>(res.values());
}
}
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int length=strs.size();
string s;
vector<vector<string> >result;
if(length==0){
result.push_back(strs);
return result;
}
map<string,vector<int> >hash;
std::map<string,vector<int> >::iterator it;
for(int i=0;i<length;i++)
{
s=strs[i];
sort(s.begin(),s.end());
hash[s].push_back(i);
}
vector<int>trans;
for(it = hash.begin(); it != hash.end(); it++){
vector<string>s1;
trans=it->second;
for(int j=0;j < trans.size();j++)
{
int x=trans[j];
s1.push_back(strs[x]);
}
result.push_back(s1);
}
return result;
}
};