LeetCode Group Anagrams

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

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

Note:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.
题意:给出一个字符串数组,将字符串按anagram分组,分组的按字符序排列。

思路:用hashMap将anagram与对应的字符串序列关联起来。

代码如下:

class Solution
{
    public List<List<String>> groupAnagrams(String[] strs)
    {
        List<List<String>> ret = new ArrayList<List<String>>();

        Map<String, List<String>> hm = new HashMap<String, List<String>>();

        for (int i = 0; i < strs.length; i++)
        {
            String tmp = strs[i];
            char[] chars = tmp.toCharArray();
            Arrays.sort(chars);
            String sorttmp = new String(chars);

            if (hm.containsKey(sorttmp))
            {
                hm.get(sorttmp).add(tmp);
            }
            else
            {
                List<String> list_str = new ArrayList<String>();
                list_str.add(tmp);
                hm.put(sorttmp, list_str);
            }
        }

        for (String str : hm.keySet())
        {
            List<String> value = hm.get(str);
            Collections.sort(value);
            ret.add(hm.get(str));
        }
        return ret;
    }
}


你可能感兴趣的:(LeetCode Group Anagrams)