1. 程式人生 > >[LeetCode]49. Group Anagrams &&雜湊演算法

[LeetCode]49. Group Anagrams &&雜湊演算法

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: All inputs will be in lower-case.

利用map實現雜湊演算法

vector<vector<string>> groupAnagrams(vector<string>& strs) {
        int len=strs.size();
	vector<vector<string> >  res;
	if(len==0)
		return res;
	 map<string,vector<string> >  temp;
	 for(int i=0;i<len;i++)
	 {
	 	string s=strs[i];
	 	sort(s.begin(),s.end());
	 	temp[s].push_back(strs[i]);
	 }
	 for(map<string,vector<string> >::iterator iter=temp.begin();iter!=temp.end();++iter)
	 {
	 	vector<string> v(iter->second);
		sort(v.begin(),v.end());
		res.push_back(v);   
	 }
	return res;
    }