LeetCode—anagrams(返回由相同字母组成的单词)—java

本文介绍了一种使用哈希映射来解决字符串分组问题的方法,该方法能够有效地找出由相同字母组成的字符串组。通过将输入的字符串数组进行排序并利用哈希表存储,可以快速地识别出所有互为字谜的字符串组。

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

题目描述

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

思路解析

  • 首先判空
  • 然后需要创建HashMap来存储排序好的字符串,以及对应有相同字母组成的ArrayList。
  • 把每个字符串Arrays.sort以后,再以HashMap的方式加入进去
  • 如果HashMap中已经有了这个key了,那么就要把,第一次放进去的value,加入到res中,说明这个是由相同字母组成的值。

代码

import java.util.*;
public class Solution {
    public ArrayList<String> anagrams(String[] strs) {
        ArrayList<String> res = new ArrayList<String>();
        if(strs==null || strs.length==0){
            return res;
        }
        HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>>();
        for(String s : strs){
            char[] ch = s.toCharArray();
            Arrays.sort(ch);
            String temp = new String(ch);
            if(hm.containsKey(temp)){
                if(hm.get(temp).size() == 1)
                    res.add(hm.get(temp).get(0));
                hm.get(temp).add(s);
                res.add(s);
            }else{
                ArrayList<String> templist = new ArrayList<String>();
                templist.add(s);
                hm.put(temp,templist);
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值