【Leetcode刷题篇】leetcode49 字母异位词分组
发布日期:2021-06-29 15:35:26 浏览次数:3 分类:技术文章

本文共 734 字,大约阅读时间需要 2 分钟。

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]

说明:

所有输入均为小写字母。
不考虑答案输出的顺序。

解法思路:用hashmap对其排序好的string作为key,而里面的为list。

class Solution {
public List
> groupAnagrams(String[] strs) {
// hashmap HashMap
> hashMap = new HashMap<>(); // 对其遍历 for(String str:strs) {
char[] arr = str.toCharArray(); Arrays.sort(arr); String key = new String(arr); // 获取list List
list = hashMap.getOrDefault(key,new ArrayList
()); list.add(str); hashMap.put(key,list); } return new ArrayList
>(hashMap.values()); }}

转载地址:https://codingchaozhang.blog.csdn.net/article/details/111429970 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Leetcode刷题篇】leetcode399 除法求值
下一篇:【Leetcode刷题篇】leetcode438 找到字符串中所有字母异位词

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月27日 07时02分21秒