当前位置:网站首页>49. 字母异位词分组:给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
49. 字母异位词分组:给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
2022-07-05 13:19:00 【?abc!】
题目描述
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
思路
从题目意思可知:
- 两个字符串互为字母异位词,需要
两个字符串包含的字母相同
- 因此对
两个字符串分别进行排序
之后得到的字符串一定是相同的 - 使用哈希表存储每一组字母异位词,
哈希表的键为一组字母异位词的标志,哈希表的值为一组字母异位词列表
将排序之后的字符串作为哈希表的键
代码
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
//哈希表的:排序之后的字符串作为哈希表的键,值为一组字母异位词列表
Map<String,List<String>> map = new HashMap<String,List<String>>();
//创建循环,遍历每一个字符串
for(String str : strs){
//将字符串拆分为字符数组
char[] array = str.toCharArray();
//对数组进行排序
Arrays.sort(array);
//将排序后的字符数组转为字符串作为map的键
String key = new String(array);
//map.getOrDefault(key,defaultValue):当Map集合中有这个key时,就使用这个key对应的value值,如果没有这个key就使用默认值defaultValue
List<String> list = map.getOrDefault(key,new ArrayList<String>());
//将当前字符串存入list集合中
list.add(str);
//将其存入map中
map.put(key,list);
}
return new ArrayList<List<String>>(map.values());
}
}
代码说明
注释见。。。
边栏推荐
- go 数组与切片
- MATLAB论文图表标准格式输出(干货)
- 私有地址有那些
- Halcon template matching actual code (I)
- The Research Report "2022 RPA supplier strength matrix analysis of China's banking industry" was officially launched
- go map
- jenkins安装
- Hiengine: comparable to the local cloud native memory database engine
- Cf:a. the third three number problem
- Principle and configuration of RSTP protocol
猜你喜欢
Hiengine: comparable to the local cloud native memory database engine
STM32 and motor development (from architecture diagram to documentation)
数据湖(七):Iceberg概念及回顾什么是数据湖
How to protect user privacy without password authentication?
记录一下在深度学习-一些bug处理
量价虽降,商业银行结构性存款为何受上市公司所偏爱?
[深度学习论文笔记]TransBTSV2: Wider Instead of Deeper Transformer for Medical Image Segmentation
“百度杯”CTF比赛 九月场,Web:Upload
Shandong University Summer Training - 20220620
【服务器数据恢复】某品牌服务器存储raid5数据恢复案例
随机推荐
Yyds dry goods inventory # solve the real problem of famous enterprises: move the round table
MySQL splits strings for conditional queries
南理工在线交流群
Cf:a. the third three number problem
leetcode 10. Regular Expression Matching 正则表达式匹配 (困难)
APICloud Studio3 API管理与调试使用教程
聊聊异步编程的 7 种实现方式
A specific example of ABAP type and EDM type mapping in SAP segw transaction code
MySQL --- 数据库查询 - 排序查询、分页查询
【Hot100】33. 搜索旋转排序数组
go map
《2022年中國銀行業RPA供應商實力矩陣分析》研究報告正式啟動
DataPipeline双料入选中国信通院2022数智化图谱、数据库发展报告
JPA规范总结和整理
Get you started with Apache pseudo static configuration
Binder通信过程及ServiceManager创建过程
【Hot100】34. Find the first and last positions of elements in a sorted array
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
Detailed explanation of navigation component of openharmony application development
#从源头解决# 自定义头文件在VS上出现“无法打开源文件“XX.h“的问题