leetcode 字谜分组 (java实现)

  我本来的思路是:通过26个字母构成长度为26的数组,这样统计每个单词都会生成对应的数组,数组相同的可以作为HashMap的键,把异位词作为值。但是后来发现数组不能作为键,索性用List直接存放每个词的字符并排序,代码如下,用时40ms:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<List<Character>, List<String>> sta = new HashMap<>();
        for (String str : strs) {
            List<Character> dict = new ArrayList<>();
            for (int i = 0; i < str.length(); ++i)
                dict.add(str.charAt(i));
            Collections.sort(dict);
            if (sta.containsKey(dict)) {
                sta.get(dict).add(str);
            }
            else {
                List<String> ls = new ArrayList<>();
                ls.add(str);
                sta.put(dict, ls);
            }
        }
        List<List<String>> re = new ArrayList<List<String>>(sta.values());
        return re;
    }
}

  后来发现最快的方法就是使用长度为26的数组作为键,只是聪明地对26位进行编码,有趣,代码中的静态变量 lenSize 应该是随意设定的,代码如下:

class Solution {
    private static int lenSize = 7;
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<Integer, List<String>> map = new HashMap();
        List<List<String>> ans = new LinkedList();

        for (int i = 0; i < strs.length; i++){
            int hash = getHash(strs[i]);
            List<String> lis = null;
            if (map.containsKey(hash))
                lis = map.get(hash);
            else {
                lis = new LinkedList();
                ans.add(lis);
                map.put(hash, lis);
            }
            lis.add(strs[i]);
        }
        return ans;
    }

    private int getHash(String str) {
        int[] vis = new int[26];
        for (int i = 0; i < str.length(); i++){
            char ch = str.charAt(i);
            vis[ch-'a']++;
        }

        int hash = 0;
        for (int i = 0; i < vis.length; i++)
            hash = hash * lenSize + vis[i];
        return hash;
    }
}

ArrayList 和 LinkedList 的大致区别,可进一步提高代码性能:
(1)ArrayList 是实现了基于动态数组的数据结构,LinkedList 基于链表的数据结构。
(2)对于随机访问 get 和 set ,ArrayList 优于 LinkedList,因为 LinkedList 要移动指针。
(3)对于新增和删除操作 add 和 remove,LinedList 比较占优势,因为 ArrayList 要移动数据。

引用与感谢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值