leetcode-anagrams

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

Note: All inputs will be in lower-case.

public class Solution {
    public List<String> anagrams(String[] strs) {
        HashMap<String,LinkedList<String>> map=new HashMap<String,LinkedList<String>>();
        List<String> result=new LinkedList<String>();
        if(strs.length==0)return result;
        /*iterate all the string*/
        for(int i=0;i<strs.length;i++){
            char[] x=strs[i].toCharArray();
            Arrays.sort(x);
            String key=String.valueOf(x);
            LinkedList cur=map.get(key);
             // if it's null, you cannot add and can only add list to it
             if(cur==null)cur=new LinkedList();
             cur.add(strs[i]);
            map.put(key,cur);   //map...
        }
        /*add the result*/
        for(String a:map.keySet()){
            if(map.get(a).size()>1){
                result.addAll(map.get(a));
            }
        }
        return result;
    }
}
思路简单,anagram的特点就是具有相同的字母组合,那么就可以利用hashmap来解决问题。

注意的问题:

1开始的时候hashmap的第二个参量list有可能是null,这时候要经过判断才能在里面加入string,不然就是nullpointer的问题。list初始化的时候只能是加入list。

2然后就是get来返回key中存储的东西,没有的时候为null。

3使用keyset来iteratekey

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值