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> groupAnagrams(vector& strs) {vector> ans;unordered_map> mp;for(int i=0; i> groupAnagrams(vector& strs) {vector> ans;unordered_map> mp;for(int i=0; i count(26, 0);//若果定义成vector来计数,计数值超过10时,字符串的对应部分会变成“10”,//这是由于10进制超过10后位数会增加导致的//会与其他本来不一样的字符串的统计计数重复,导致对key的判断相同;所以使用char类型//从ascii的0开始,至少有128个不重复字符来用于计数,相当于128进制的数string str;stringstream ss;for(int j=0; j(ss, ""));str = ss.str();cout<> groupAnagrams(vector& strs) {vector> ans;unordered_map> mp;for(int i=0; i,避免了将其转化为string的步骤for(int j=0; j
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 不希望用户直接操作这几个方法的返回值。
标准库类型 vector: push_back()
关联容器 map,set,unsorted_map等,就相当于python里的defaultdict;first是key,second是value
自动类型:auto i: mp
下一篇:Java-接口