当前位置:网站首页>力扣.字母异位词分组
力扣.字母异位词分组
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;
}
};
边栏推荐
- opencv之访问图像像素的三种方法
- wangeditor编辑器内容传至后台服务器存储
- 超参数优化-摘抄
- Cholesterol-PEG-Acid CLS-PEG-COOH Cholesterol-Polyethylene Glycol-Carboxyl Modified Peptides
- Hyperparameter Optimization - Excerpt
- 2021-09-30
- 2021-09-30
- Wangeditor rich text editor to upload pictures and solve cross-domain problems
- Cholesterol-PEG-Azide CLS-PEG-N3 胆固醇-聚乙二醇-叠氮 MW:3400
- 化学试剂磷脂-聚乙二醇-氨基,DSPE-PEG-amine,CAS:474922-26-4
猜你喜欢

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

MySQL 免安装版的下载与配置教程

【Rhapsody学习笔记】1:Hello World

四种常见的POST提交数据方式

mPEG-DSPE 178744-28-0 甲氧基-聚乙二醇-磷脂酰乙醇胺线性PEG磷脂

DSPE-PEG-COOH CAS:1403744-37-5 磷脂-聚乙二醇-羧基脂质PEG共轭物

Detailed explanation of mysql transaction principle

mPEG-DSPE 178744-28-0 Methoxy-polyethylene glycol-phosphatidylethanolamine linear PEG phospholipids

Fluorescein-PEG-DSPE Phospholipid-Polyethylene Glycol-Fluorescein Fluorescent Phospholipid PEG Derivatives

Numpy常用函数
随机推荐
IDEA概述和安装及调试
浏览器中的画中画(Picture-in-Picture)API
Detailed explanation of mysql transaction principle
Pytorch study notes 7 - processing input of multi-dimensional features
The array technique, my love
MySQL 免安装版的下载与配置教程
变分自编码器VAE实现MNIST数据集生成by Pytorch
自然语言处理相关list
The content of the wangeditor editor is transferred to the background server for storage
应用usb_cam同时打开多个摄像头方法
cv2.resize()是反的
Redis-Hash
MW: 3400 4-Arm PEG-DSPE four-arm-polyethylene glycol-phospholipid a saturated 18-carbon phospholipid
Virtual machine view port number process
Session和Cookie,Token
ROS 之订阅多个topic时间同步问题
Wangeditor rich text editor to upload pictures and solve cross-domain problems
Use usb_cam to open multiple cameras at the same time
DSPE-PEG-Thiol DSPE-PEG-SH phospholipid-polyethylene glycol-thiol liposome for later use
Four common ways of POST to submit data