当前位置:网站首页>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());
}
}
代码说明
注释见。。。
边栏推荐
猜你喜欢

阿里云SLB负载均衡产品基本概念与购买流程

Backup and restore of Android local SQLite database

PyCharm安装第三方库图解

ABAP editor in SAP segw transaction code

Discussion on error messages and API versions of SAP ui5 getsaplogonlanguage is not a function

Can and can FD

数据泄露怎么办?'华生·K'7招消灭安全威胁

聊聊异步编程的 7 种实现方式

Navigation property and entityset usage in SAP segw transaction code

jenkins安装
随机推荐
Get you started with Apache pseudo static configuration
Rocky基础命令3
碎片化知识管理工具Memos
Realize the addition of all numbers between 1 and number
Jenkins installation
[deep learning paper notes] hnf-netv2 for segmentation of brain tumors using multimodal MR imaging
go 指针
Shu tianmeng map × Weiyan technology - Dream map database circle of friends + 1
uni-app开发语音识别app,讲究的就是简单快速。
Datapipeline was selected into the 2022 digital intelligence atlas and database development report of China Academy of communications and communications
MySQL splits strings for conditional queries
Solve Unicode decodeerror: 'GBK' codec can't decode byte 0xa2 in position 107
There is no monitoring and no operation and maintenance. The following is the commonly used script monitoring in monitoring
同事半个月都没搞懂selenium,我半个小时就给他整明白!顺手秀了一波爬淘宝的操作[通俗易懂]
一文详解ASCII码,Unicode与utf-8
Win10——轻量级小工具
什么是网络端口
UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xe6 in position 76131: invalid continuation byt
RHCSA10
The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)