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.
题意:
给定一个包含若干字符串的数组,将所有含有相同字符的字符串合并为一组,返回最终结果。
思路:
最直接的思路,可以直接对所有字符进行排序后选择置为相应的结果中。因为,相同组的字符串所包含的字符个数相等,因此排序后所得到的字符串相等,即可置入相应的组合中,可借助unordered_map实现。
Code & C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
std::ios::sync_with_stdio(0);
cin.tie(0);
unordered_map<string, vector<string>> mp;
for(string s:strs){
mp[strSort(s)].push_back(s);
}
vector<vector<string>> ans;
for(auto p:mp){
ans.push_back(p.second);
}
return ans;
}
private:
string strSort(string s){
int c[26]={0};
for(char ch:s){
++c[ch-'a'];
}
string ans;
for(int i=0;i<26;++i){
ans += string(c[i],i+'a');
}
return ans;
}
};
这里使用strSort代替STL中的sort函数,是因为保证了所有字符均为小写字母,这样可相应减少部分开销。
Code & Python
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ans = collections.defaultdict(list)
for s in strs:
c = [0]*26
for t in s:
c[ord(t)-ord('a')] +=1
ans[tuple(c)].append(s)
return ans.values()