用哈希桶實現錯位字組的分類(Group Anagrams)

一、學習要點:
1.map和unordered_map的區別;
2.哈希桶的使用;
二、代碼:

class Solution
{
public:
	vector<vector<string>> groupAnagrams(vector<string>& strs)
	{
		vector<vector<string>> res;
		unordered_map<string,vector<string>> ;
		for(string str:strs)
		{
			string t=str;
			sort(t.begin(),t.end());
			m[t].push_back(str);
		}
		for(auto a:m)
		{
			res.push_back(a.second);
		}
		return res;
	}
};
int main() {
 vector<string> strs;
 vector<vector<string>> res;
 Solution obj;
 strs = {"rea","aer","aer","tue"};
 res =obj.groupAnagrams(strs);
 for (auto s : res) {
  for (string ss : s)
  {
   cout<<ss << ",";
   //printf("%s,", ss.c_str());
  }
  cout<<endl;
 }
 system("pause");
 return 0;
}

三、運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章