当前位置:网站首页>力扣.字母异位词分组
力扣.字母异位词分组
2022-07-31 05:17:00 【旺仔 小馒头】
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
思路
首先遇到异位词,一定要想到用hash表来解决,首先字符串是无序的,我们可以通过STL中的sort方法将字符串排序,这样所有的异位词都会变成同一种排列顺序的串,于是遍历这个字符串数组,将对应的串当作hash表的键值key,将排序以前的串当作key对应的value,因为返回的仍然是一条条串组成的数组,所以map对应的value类型不能是普通的string,而是一个vector<string>, vector容器中的元素是各种字符串。
(意思就是:建立一个unordered_map<string ,vector<string> >一个字符串 ,str排序后当作key,排序前当value中的一个个子集)。
遍历strs,遇到相同key的串就添加进容器。
代码如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 用于接收最后的结果
vector<vector<string>> ret;
// 建立一个hash_map
unordered_map<string,vector<string>> m;
for (auto& str : strs){
// 这里一定需要一个中间变量,如果直接用m[str].push_back(str),
// str会在排序后错乱,最终插入的str顺序不再是之前的顺序而是排过序后的
string key = str;
// 将字符串进行排序,这样异位词排序后,都是一样的key
sort(key.begin(),key.end());
// 用相同的key当作键值,并将其对应的原字符串当作value,压入value的vector容器
m[key].push_back(str);
}
// 最终遍历m,将相同key对应的value(一个vector<string>容器:存着各种异位词串),分别压入ret
// 容器中
for (auto e : m)
ret.push_back(e.second);
return ret;
}
};
边栏推荐
- 解决nx安装 jtop问题
- Attention based ASR(LAS)
- ROS之service传输图片
- When solving background-size:cover, the picture is covered but not displayed completely?
- 2022年SQL大厂高频实战面试题(详细解析)
- mysql 事务原理详解
- 关于Iframe
- Data Preprocessing, Feature Engineering, and Feature Learning - Excerpt
- Software Testing Interview Questions 2021
- 这些数组技巧,我爱了
猜你喜欢

Remote file xxx is mapped to the local path xxx and can‘t be found. You can continue debugging....

Pytorch学习笔记09——多分类问题

Picture-in-Picture API in the browser

DSPE-PEG-COOH CAS: 1403744-37-5 Phospholipid-polyethylene glycol-carboxy lipid PEG conjugate

UR3机器人运动学分析之逆运动学分析

2021-09-30

MySQL 主从切换步骤

钉钉企业内部-H5微应用开发

IDEA概述和安装及调试

Tensorflow边用边踩坑
随机推荐
ImportError: cannot import name ‘Xxxx‘ from partially initialized module ‘xx.xx.xx‘
Solution for MySQL The table is full
Cholesterol-PEG-DBCO Cholesterol-Polyethylene Glycol-Diphenylcyclooctyne Chemical Reagent
Jupyter内核正忙、内核挂掉
ROS subscription to multiple topics time synchronization problem
cocos2d-x-3.2 create project method
CAS:474922-22-0 Maleimide-PEG-DSPE Phospholipid-Polyethylene Glycol-Maleimide Brief Description
DSPE-PEG-Thiol DSPE-PEG-SH 磷脂-聚乙二醇-巯基脂质体制备用
数据预处理、特征工程和特征学习-摘抄
解决background-size:cover时图片铺满但显示不完整?
MySQL 入门:Case 语句很好用
opencv之图像二值化处理
深度学习知识点杂谈
MySQL 免安装版的下载与配置教程
MySQL 出现 The table is full 的解决方法
Phospholipids-Polyethylene Glycol-Active Esters for Scientific Research DSPE-PEG-NHS CAS: 1445723-73-8
Data Preprocessing, Feature Engineering, and Feature Learning - Excerpt
IDEA overview and installation and debugging
MW: 3400 4-Arm PEG-DSPE four-arm-polyethylene glycol-phospholipid a saturated 18-carbon phospholipid
词向量——demo