当前位置:网站首页>leetcode: 49. 字母异位词分组
leetcode: 49. 字母异位词分组
2022-06-25 21:32:00 【uncle_ll】
49. 字母异位词分组
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/group-anagrams/
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
- 1 <= strs.length <= 1 0 4 10^4 104
- 0 <= strs[i].length <= 100
- strs[i] 仅包含小写字母
解法
- 排序+哈希表:对每一个字符串做排序后,作为哈希表的key,这样就能将包含相同元素的字符串归类到一起;
- 计数+哈希表:由于互为字母异位词的两个字符串包含的字母相同,因此两个字符串中的相同字母出现的次数一定是相同的,故可以将每个字母出现的次数使用字符串表示,作为哈希表的键;
代码实现
排序+哈希表
python实现
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
counts = dict()
for s in strs:
ss = ''.join(sorted(s))
if ss in counts:
counts[ss].append(s)
else:
counts[ss] = [s]
return list(counts.values())
c++实现
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> counts;
for(auto str: strs) {
string ss = str;
sort(ss.begin(), ss.end());
auto it = counts.find(ss);
if (it != counts.end())
counts[ss].push_back(str);
else
counts[ss] = {
str};
}
vector<vector<string>> ans;
for (auto it=counts.begin(); it != counts.end(); it++) {
ans.push_back(it->second);
}
return ans;
}
};
复杂度分析
- 时间复杂度: O ( K N l o g K ) O(KNlogK) O(KNlogK) N是strs中字符串的数量,K是strs中字符串最大长度
- 空间复杂度: O ( K N ) O(KN) O(KN)
计数+哈希表
python实现
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
mp = collections.defaultdict(list)
for st in strs:
counts = [0] * 26
for ch in st:
counts[ord(ch) - ord("a")] += 1
# 需要将 list 转换成 tuple 才能进行哈希, list不能作为key
mp[tuple(counts)].append(st)
return list(mp.values())
c++实现
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int n=strs.size();
if(n==1) return vector<vector<string>>{
{
strs[0]}};
vector<vector<string>> res;
unordered_map<string,int> mp;
int index=0;
for(int i=0;i<n;i++){
string str=strs[i];
string count(26,0);
for(int j=0;j<str.size();j++){
count[str[j]-'a']++;
}
if(mp.find(count)!=mp.end())res[mp[count]].push_back(str);
else {
mp[count]=index;
res.push_back(vector<string>{
str});
index++;
}
}
return res;
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( N ) O(N) O(N)
注意
Python中字典的key都可以是什么?
答:python中字典的key不能是可变类型。字典可存储任意类型对象,其中值可以取任何数据类型,但键必须是不可变的,如字符串、数字或元组。
一个对象能不能作为字典的key,就取决于其有没有__hash__方法。所以所有python自带类型中,除了list、dict、set和内部至少带有上述三种类型之一的tuple之外,其余的对象都能当key。
边栏推荐
- Php7.4 arm environment compilation and installation error invalid 'ASM': invalid operate prefix '%c'
- multiplication table
- CANoe. Diva operation guide TP layer test
- Docker Alpine image installation PHP extension redis
- Canoe learning notes (2)
- Pat 1083 list grades (25 points)
- [nailing scenario capability package] manage the on-the-job / off-the-job situation of employees
- Zhiyun health is about to go public: long-term losses, meinian health Yu Rong has withdrawn, and it is difficult to be optimistic about the future
- [nailing scenario capability package] company / Park Digital canteen
- Huawei switch stack configuration
猜你喜欢

Explain memcached principle in detail

HNU计网实验:实验一 应用协议与数据包分析实验(使用Wireshark)

Canoe learning notes (3)

Jmeter- (IV) regular expression for interface testing

What is a ZFS file system

Differences between modems and routers (powercert animated videos)

PHP Chinese word segmentation API, Harbin Institute of technology ltpcloud, naturallanguageprocessing, free, best practices!

Using two stacks to realize the function of one queue?

The latest (2022-2-16) vulnerability of WordPress plug-in bee collection (XSS, WordPress user name exposure, arbitrary article publishing) is repeated

On merging and sorting
随机推荐
Support JPEG format in GD Library in php7.4
Jmeter- (I) installation of interface test
Finger collar pin exclusive Medal
05 configuring network parameters
Type conversion basis
multiplication table
UDP Vs TCP (Powercert animated videos)
The robotframework executes JS commands to move the mouse from X to y
Illustration tcp/ip - Chapter 1 and 2 Notes
Win11录屏数据保存在哪里?Win11录屏数据保存的位置
Get parameters in URL
Differences between modems and routers (powercert animated videos)
PHP compressed file
JS__ This, arguments, cloning, ternary operator__ Duyi
Working principle and experimental analysis of DHCP
ThreadLocal class
What is a server? (Powercert animated videos)
Free cloud function proxy IP pool just released
Renren mall locates the file according to the route
For loop averaging