Given an array of strings, group anagrams together.
Note: All inputs will be in lowercase. The order of your output does not matter.
給予一個字串的陣列,將同樣的字謎組合組在一起。 (所謂的同樣的字謎指每個字串內含的字母完全一樣,連數量都一樣,只是排列組合不同) 注意: 所有輸入都是小寫字母。 你輸出結果的先後順序並不重要。
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<string> strs_sort(strs); map<string, vector<string>> map_ans; vector<vector<string>> ans; for(int i = 0; i < strs.size(); i++) sort(strs_sort[i].begin(), strs_sort[i].end()); for(int i = 0; i < strs.size(); i++) { if(map_ans.find(strs_sort[i]) == map_ans.end()) map_ans[strs_sort[i]] = vector<string>(); map_ans[strs_sort[i]].push_back(strs[i]); } for(auto it : map_ans) ans.push_back(it.second); return ans; } };
LeetCode
C++
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up