Group Anagram

来源:互联网 发布:js 点击按钮刷新div 编辑:程序博客网 时间:2024/05/16 03:54

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.
public List<List<String>> groupAnagrams(String[] strs) {int n = strs.length;List<List<String>> res = new ArrayList<List<String>>();if (n <= 0)return res;HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();ArrayList<String> temp = null;String str = null;for (int i = 0; i < n; i++) {char[] key = strs[i].toCharArray();Arrays.sort(key);str = new String(key);if (map.containsKey(str)) {temp = map.get(str);temp.add(strs[i]);} else {temp = new ArrayList<String>();temp.add(strs[i]);map.put(str, temp);}}Collection<ArrayList<String>> values = map.values();for (ArrayList<String> r : values) {Collections.sort(r);if (r.size() >= 1)res.add(r);}return res;}

http://blog.csdn.net/lmy690858904/article/details/48517361

http://blog.csdn.net/fly_yr/article/details/48163005

0 0