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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> ans = new LinkedList<>(); for (String str : strs) { insert(ans, str); } return ans; }
private void insert(List<List<String>> ans, String word) { boolean flag = false; for (var group : ans) { if (group.isEmpty()) { continue; } String head = group.get(0); if (anagram(head, word)) { flag = true; group.add(word); break; } } if (!flag) { ans.add(new LinkedList<>(List.of(word))); } }
private boolean anagram(String word1, String word2) { if (word1.length() != word2.length()) { return false; } int[] count1 = new int[26]; int[] count2 = new int[26]; for (int i = 0; i < word1.length(); i++) { count1[word1.charAt(i) - 'a']++; count2[word2.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if (count1[i] != count2[i]) { return false; } } return true; } }
|