题目链接:https://leetcode.com/problems/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:
public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> strss = new ArrayList<List<String>>(); HashMap<String, List<String>> maps = new HashMap<String, List<String>>(); for (String s : strs) { // 字符串内排序,并保存对应关系 char c[] = s.toCharArray(); Arrays.sort(c); if (!maps.containsKey(String.valueOf(c))) { List<String> l = new ArrayList<String>(); l.add(s); maps.put(String.valueOf(c), l); } else { List<String> l = maps.get(String.valueOf(c)); l.add(s); maps.put(String.valueOf(c), l); } } Iterator<String> set = maps.keySet().iterator(); while (set.hasNext()) { List<String> l = maps.get(set.next()); Collections.sort(l); // 因为要求list内部字符串要字典序,所以对list进行排序,可以用collections对list排序 strss.add(l); } return strss; }