1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Solution { public List<List<String>> groupAnagrams(String[] strs) { if (strs == null || strs.length == 0) return new ArrayList<List<String>>(); HashMap<String, List<String>> lookup = new HashMap<String, List<String>>(); Arrays.sort(strs); for (int i = 0; i < strs.length; i++){ char[]label = strs[i].toCharArray(); Arrays.sort(label); String key = String.valueOf(label); if (!lookup.containsKey(key)){ lookup.put(key, new ArrayList<String>()); } lookup.get(key).add(strs[i]); } return new ArrayList<List<String>>(lookup.values()); } } |
Saturday, November 28, 2015
[leetcode] Group anagrams
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment