題目鏈接
tag:
- Medium;
question:
??Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
思路:
??這道題讓我們?nèi)航M給定字符串集中所有的錯(cuò)位詞,所謂的錯(cuò)位詞就是兩個(gè)字符串中字母出現(xiàn)的次數(shù)都一樣,只是位置不同,比如abc,bac, cba等它們就互為錯(cuò)位詞,那么我們?nèi)绾闻袛鄡烧呤欠袷清e(cuò)位詞呢,我們發(fā)現(xiàn)如果把錯(cuò)位詞的字符順序重新排列,那么會(huì)得到相同的結(jié)果,所以重新排序是判斷是否互為錯(cuò)位詞的方法,由于錯(cuò)位詞重新排序后都會(huì)得到相同的字符串,我們以此作為key,將所有錯(cuò)位詞都保存到字符串?dāng)?shù)組中,建立key和字符串?dāng)?shù)組之間的映射,最后再存入結(jié)果res中即可,AC代碼如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
string s = str;
sort(s.begin(), s.end());
m[s].push_back(str);
}
for (auto a : m)
res.push_back(a.second);
return res;
}
};