49.字母异位词分组

学习unordered_map[1]

// C++ program to demonstrate functionality of unordered_map 
#include  
#include  
using namespace std; 

int main() 
{ 
	// Declaring umap to be of  type 
	// key will be of string type and mapped value will 
	// be of double type 
	unordered_map<string, int> umap; 

	// inserting values by using [] operator 
	umap["GeeksforGeeks"] = 10; 
	umap["Practice"] = 20; 
	umap["Contribute"] = 30; 

	// Traversing an unordered map 遍历key---value
	for (auto x : umap) 
	cout << x.first << " " << x.second << endl; 

} 

分析:由于错位词重新排序后都会得到相同的字符串,我们以此作为key,将所有错位词都保存到字符串数组中,建立key和字符串数组之间的映射,最后再存入结果res中即可。

1.c++ code AC 97%:

class Solution {
 public:
	 vector<vector<string>> groupAnagrams(vector<string>& strs) {
		 vector<vector<string>>res;
		 if (strs.size() == 0)return res;
		 unordered_map<string, vector<string>>M;
		 for (string i : strs)
		 {
			 string Temp = i;
			 sort(i.begin(), i.end());
			 M[i].push_back(Temp);//同一个key:abc存放value:bac,cab
		 }
		 for (auto i : M)
			 res.push_back(i.second);
		 return res;
	 }
 };

[1]https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/
[2]https://www.cnblogs.com/ariel-dreamland/p/9143262.html

你可能感兴趣的:(leetcode题,leetcode)