- Difficulty: Medium
Given an array of strings, group anagrams together.
For example, given:
Return:
["eat", "tea", "tan", "ate", "nat", "bat"]
, Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Company:
思路: Use HashMap to track each anagram as key, and store the strings in values
The key is fixed for anagrams by sorting string alphabetically(conver toCharArray() & Arrays.sort).
关键字:Sort String,HashMap
public class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap<String,List<String>>map = new HashMap<String,List<String>>(); for(String s:strs){ char[] tmp = s.toCharArray();//sort string Arrays.sort(tmp); String key = new String(tmp); if(!map.containsKey(key)) map.put(key,new ArrayList<String>()); map.get(key).add(s); } return new ArrayList<List<String>>(map.values()); } }
No comments:
Post a Comment