LeetCode 49. Group Anagrams(哈希)

题目来源:https://leetcode.com/problems/group-anagrams/

问题描述

49. Group Anagrams

Medium

1483103FavoriteShare

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],

Output:

[

  ["ate","eat","tea"],

  ["nat","tan"],

  ["bat"]

]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

------------------------------------------------------------

题意

把字符串List中字母相同的字符串(如aababa,但aabaaab不是)归到一个List中去,输出整理好的List

------------------------------------------------------------

思路

用HashMap记录相同字母组成的字符串序列。用另外一个HashMap或26位int数组记录每个字符串的字符组成,以此作为前面提到的HashMap的key。

其中要注意的是Array的hashCode和equals方法是引用的hashCode和equals,不能用于比较两个Array的值是否相同。而List的hashCode和equals方法可以用于比较两个List的值是否相同。因此如果采用Array记录字符组成,要将其转换为List再作为HashMap的key.

------------------------------------------------------------

代码

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<List<Integer>, List<String>> map = new HashMap<List<Integer>, List<String>>();
        for (String s: strs)
        {
            int[] cnt = new int[26];
            for (char ch: s.toCharArray())
            {
                cnt[ch - 'a']++;
            }
            List<Integer> cntList = Arrays.stream(cnt).boxed().collect(Collectors.toList());
            if (map.containsKey(cntList))
            {
                map.get(cntList).add(s);
            }
            else
            {
                map.put(cntList, new LinkedList<String>(){
                    {
                        add(s);
                    }
                });
            }
        }
        return new LinkedList<>(map.values());
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/89161652
今日推荐