leetcode Group Anagrams

本文介绍了一种用于将字符串按字母异位词进行分组的算法。该算法通过将输入的字符串数组中的每个字符串进行排序并作为键存储在哈希表中来实现。最终输出的是一个列表,其中包含所有按字母异位词分组的字符串列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

这个题目的思想就是
拿到一个字符串,然后排序。然后到hash表里面找到对应的加进去。。最后对表进行排序。ok

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
         HashMap<String, List<String>> hashMap=new HashMap<>();
        for (String string2: strs) {
            char[]key=string2.toCharArray();
            Arrays.sort(key);
            String keyStr=new String(key);
            List<String> theGet=hashMap.get(keyStr);
            if(theGet==null)
            {
                theGet=new LinkedList<String>();

                hashMap.put(keyStr,theGet);
            }
            theGet.add(string2);
        }

        List<List<String>> result=new ArrayList<List<String>>(hashMap.size());
        Set<String> keySet=hashMap.keySet();

        for (String string : keySet) {
            List<String> row=hashMap.get(string);
            String[] rowStr=new String[row.size()];
            row.toArray(rowStr);
            Arrays.sort(rowStr);
            ArrayList<String> tempResult=new ArrayList<String>(row.size());
            for(int i=0;i<rowStr.length;i++)
            {
                tempResult.add(rowStr[i]);
            }
            result.add(tempResult);
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值