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.
利用JAVA中字符串会固定内存地址。(因此在进行字符串操作时是生成了新的对象。)
遍历每个单词,记录26个字母出现的次数,并映射到字符数组上。
将字符数组转换成字符串,生成一个新的字符串。
将字符串作为key放入map中,value储存原有单词。(字符串的内存地址固定,因此同样的字符串可以被搜索到。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> ret = new ArrayList<>(); HashMap<String, List<String>> map = new HashMap<>(); for(String word : strs){ char[] alphabet = new char[26]; for(int j = 0; j < word.length(); j++){ alphabet[word.charAt(j)-'a']++; } String s = new String(alphabet); List<String> str = map.getOrDefault(s, new ArrayList<String>()); str.add(word); map.put(s, str); } for(String key : map.keySet()){ ret.add(map.get(key)); } return ret; } }
|