|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=49 lang=java |
| 3 | + * |
| 4 | + * [49] Group Anagrams |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/group-anagrams/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (46.25%) |
| 10 | + * Likes: 1856 |
| 11 | + * Dislikes: 120 |
| 12 | + * Total Accepted: 370.8K |
| 13 | + * Total Submissions: 768.1K |
| 14 | + * Testcase Example: '["eat","tea","tan","ate","nat","bat"]' |
| 15 | + * |
| 16 | + * Given an array of strings, group anagrams together. |
| 17 | + * |
| 18 | + * Example: |
| 19 | + * |
| 20 | + * |
| 21 | + * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], |
| 22 | + * Output: |
| 23 | + * [ |
| 24 | + * ["ate","eat","tea"], |
| 25 | + * ["nat","tan"], |
| 26 | + * ["bat"] |
| 27 | + * ] |
| 28 | + * |
| 29 | + * Note: |
| 30 | + * |
| 31 | + * |
| 32 | + * All inputs will be in lowercase. |
| 33 | + * The order of your output does not matter. |
| 34 | + * |
| 35 | + * |
| 36 | + */ |
| 37 | +class Solution { |
| 38 | + public List<List<String>> groupAnagrams(String[] strs) { |
| 39 | + if (strs.length == 0) return new ArrayList(); |
| 40 | + |
| 41 | + Map<String, List<String>> map = new HashMap<>(); |
| 42 | + int[] count = new int[26]; |
| 43 | + |
| 44 | + for (String str : strs) { |
| 45 | + Arrays.fill(count, 0); |
| 46 | + for (char ch : str.toCharArray()) { |
| 47 | + count[ch - 'a']++; |
| 48 | + } |
| 49 | + |
| 50 | + StringBuilder sb = new StringBuilder(); |
| 51 | + for (int i = 0; i < count.length; i++) { |
| 52 | + sb.append("#"); |
| 53 | + sb.append(count[i]); |
| 54 | + } |
| 55 | + String key = sb.toString(); |
| 56 | + |
| 57 | + if (!map.containsKey(key)) { |
| 58 | + map.put(key, new ArrayList()); |
| 59 | + } |
| 60 | + map.get(key).add(str); |
| 61 | + } |
| 62 | + |
| 63 | + return new ArrayList(map.values()); |
| 64 | + } |
| 65 | +} |
0 commit comments