Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
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
| class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap<String, List<String>> map = new HashMap<>(); //主要思路是利用sort,将eat,ate,tea全部sort成aet //然后在hashmap里找,如果有相同的就加入map for(int i = 0; i < strs.length; i++) { char[] letter = strs[i].toCharArray(); Arrays.sort(letter); String key = String.valueOf(letter); //String ley store values sorted //key: "aet" if(map.containsKey(key)) { map.get(key).add(strs[i]); } else { List<String> tempList = new ArrayList<>(); tempList.add(strs[i]); map.put(key, tempList); } } return new ArrayList<List<String>>(map.values()); } }
|