题目名称
- Group Anagrams
题目描述
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
Example 2:
Input: strs = [“”]
Output: [[“”]]
Example 3:
Input: strs = [“a”]
Output: [[“a”]]
初试思路
1、排序
2、数字母
初试代码
// 我的代码1-python
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
// 我的代码1-c++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string, vector<string>> mp;
for(int i=0; i<strs.size(); i++){
string s = strs[i];
sort(strs[i].begin(), strs[i].end());
mp[strs[i]].push_back(s);
}
for(auto i : mp){
ans.push_back(i.second);
}
return ans;
}
};
// 我的代码2-python
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
count = [0]*26
for c in s:
count[ord(c)-ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
// 我的代码2-c++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string, vector<string>> mp;
for(int i=0; i<strs.size(); i++){
vector<char> count(26, 0);//若果定义成vector<int>来计数,计数值超过10时,字符串的对应部分会变成“10”,
//这是由于10进制超过10后位数会增加导致的
//会与其他本来不一样的字符串的统计计数重复,导致对key的判断相同;所以使用char类型
//从ascii的0开始,至少有128个不重复字符来用于计数,相当于128进制的数
string str;
stringstream ss;
for(int j=0; j<strs[i].size(); j++){
count[strs[i][j]-'a']++;
cout<<strs[i][j]-'a'<<':'<<count[strs[i][j]-'a']<<endl;
}
copy(count.begin(), count.end(), ostream_iterator<char>(ss, ""));
str = ss.str();
cout<<str<<endl;
mp[str].push_back(strs[i]);
}
for(auto i : mp){
ans.push_back(i.second);
}
return ans;
}
};
// 我的代码2-c++_
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string, vector<string>> mp;
for(int i=0; i<size(strs); i++){
string s(26,0); //直接用string代替vector<char>,避免了将其转化为string的步骤
for(int j=0; j<size(strs[i]); j++){
s[strs[i][j]-'a']++;
}
mp[s].push_back(strs[i]);
}
for(auto i : mp){
ans.push_back(i.second);
}
return ans;
}
};
学到了啥
python
python内建模块collections, 内建函数ord(‘a’)=97。
Python中通过Key访问字典,当Key不存在时,会引发‘KeyError’异常。为了避免这种情况的发生,可以使用collections类中的defaultdict()方法来为字典提供默认值。
语法格式:
collections.defaultdict([default_factory[, …]])
该函数返回一个类似字典的对象。defaultdict是Python内建字典类(dict)的一个子类,它重写了方法_missing_(key),增加了一个可写的实例变量default_factory,实例变量default_factory被missing()方法使用,如果该变量存在,则用以初始化构造器,如果没有,则为None。其它的功能和dict一样。
关于dict的操作:
将这三个方法放在一起介绍,是因为它们都用来获取字典中的特定数据:
keys() 方法用于返回字典中的所有键(key);
values() 方法用于返回字典中所有键对应的值(value);
items() 用于返回字典中所有的键值对(key-value)。
需要注意的是,在 Python 2.x 中,上面三个方法的返回值都是列表(list)类型。但在 Python 3.x 中,它们的返回值并不是我们常见的列表或者元组类型,因为 Python 3.x 不希望用户直接操作这几个方法的返回值。
c++
标准库类型 vector: push_back()
关联容器 map,set,unsorted_map等,就相当于python里的defaultdict;first是key,second是value
自动类型:auto i: mp