LeetCode 49. Group Anagrams
原题链接在这里: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: All inputs will be in lower-case.
题解:
用sort的方式找出anagram的base型,用来当HashMap的key.
Time Complexity: O(nlogn * strs.length), n是strs中最长string的长度. Space: O(hm.size()), HashMap size.
AC Java:
1 class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 HashMap<String, List<String>> hm = new HashMap<>(); 4 for(String s : strs){ 5 char [] sArr = s.toCharArray(); 6 Arrays.sort(sArr); 7 String sortedStr = new String(sArr); 8 9 hm.putIfAbsent(sortedStr, new ArrayList<>()); 10 hm.get(sortedStr).add(s); 11 } 12 13 return new ArrayList<List<String>>(hm.values()); 14 } 15 }