当前位置:网站首页>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());
}
}
代码说明
注释见。。。
边栏推荐
- 个人组件 - 消息提示
- 关于 Notion-Like 工具的反思和畅想
- Fragmented knowledge management tool memos
- [daily question] 1200 Minimum absolute difference
- “百度杯”CTF比赛 九月场,Web:SQL
- go 字符串操作
- 【Hot100】34. Find the first and last positions of elements in a sorted array
- Android本地Sqlite数据库的备份和还原
- [深度学习论文笔记]TransBTSV2: Wider Instead of Deeper Transformer for Medical Image Segmentation
- LB10S-ASEMI整流桥LB10S
猜你喜欢
Actual combat simulation │ JWT login authentication
Android本地Sqlite数据库的备份和还原
Concurrent performance test of SAP Spartacus with JMeter
精彩速递|腾讯云数据库6月刊
Word document injection (tracking word documents) incomplete
Flutter 3.0更新后如何应用到小程序开发中
数据湖(七):Iceberg概念及回顾什么是数据湖
Jenkins installation
leetcode:221. Maximum square [essence of DP state transition]
百度杯”CTF比赛 2017 二月场,Web:爆破-2
随机推荐
爱可生SQLe审核工具顺利完成信通院‘SQL质量管理平台分级能力’评测
[notes of in-depth study paper]uctransnet: rethink the jumping connection in u-net from the perspective of transformer channel
百度杯”CTF比赛 2017 二月场,Web:爆破-2
Discussion on error messages and API versions of SAP ui5 getsaplogonlanguage is not a function
JS to determine whether an element exists in the array (four methods)
DataPipeline双料入选中国信通院2022数智化图谱、数据库发展报告
Detailed explanation of navigation component of openharmony application development
mysql econnreset_Nodejs 套接字报错处理 Error: read ECONNRESET
Binder通信过程及ServiceManager创建过程
Rocky基础知识1
从外卖点单浅谈伪需求
聊聊异步编程的 7 种实现方式
DataPipeline双料入选中国信通院2022数智化图谱、数据库发展报告
restTemplate详解
Integer ==比较会自动拆箱 该变量不能赋值为空
Cloudcompare - point cloud slice
今年上半年,通信行业发生了哪些事?
jenkins安装
The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
Lb10s-asemi rectifier bridge lb10s