LeetCode 49. 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: All inputs will be in lower-case.

题意:把应用同样字母的单词,放在一个里面,我这里采用的方法是排序,然后判断是否已经具有了这个主键了,有的话直接放在后面,没有的话,创建一个新的放在后面。

public static List> groupAnagrams(String[] strs) {
        List> list = new ArrayList<>();
        HashMap helper = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            if (helper.containsKey(key)) {
                list.get(helper.get(key)).add(strs[i]);
            } else {
                List temp = new ArrayList<>();
                temp.add(strs[i]);
                list.add(temp);
                helper.put(key, list.size() - 1);
            }
        }
        return list;
    }

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