[算法练习及思路-leetcode每日一题(Java解法)]No49.字母异位词分组

134 篇文章 1 订阅
28 篇文章 0 订阅

题号:no49

题目名:字母异位词分组
原题URL:https://leetcode-cn.com/problems/group-anagrams-lcci/
题目描述

编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

示例

示例 1:

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

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

1.遍历每个字符串

2.每个字符串,如果是变了位置的字符串,那他们经过排序后得到的这个key肯定是不变的.这里也可以用字母表来记录

3.然后就是map的存取问题了.

解题代码
class Solution {
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> groupAnagrams(String[] strs) {
        //遍历每一个字符串
        //排序字符串以后,如果是异位词语,排序后肯定相同,用hash散列表去存储对应的List
        Map<String,List<String>> str2list = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> list = str2list.get(key);
            if(list ==null) {
                list = new ArrayList<>();
                res.add(list);
            }
            list.add(str);
            str2list.put(key,list);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值