
Problem Description
题目很简单,写blog的意义在于,记住如何使用map的iterator,如何对String做排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> ans = new ArrayList<List<String>>(); if (strs == null || strs.length == 0) return ans; HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for (String str : strs) { String key = sort(str); if (map.containsKey(key)) { map.get(key).add(str); } else { List<String> list = new ArrayList<String>(); list.add(str); map.put(key, list); } } Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); Collections.sort((List)pair.getValue()); ans.add((List)pair.getValue()); } return ans; }
public String (String str) { char[] array = str.toCharArray(); Arrays.sort(array); String ans = new String(array); return ans; }
|
近期评论