49. Group Anagrams
Difficulty: Medium
Related Topics: Hash Table, String
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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 10<sup>4</sup>
0 <= strs[i].length <= 100
strs[i]
consists of lower-case English letters.
Solution
Language: Java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
int[] a = new int[127];
a['a']=2; a['b']=3; a['c']=5;
a['d']=7; a['e']=11; a['f']=13;
a['g']=17; a['h']=19; a['i']=23;
a['j']=29; a['k']=31; a['l']=37;
a['m']=41; a['n']=43; a['o']=47;
a['p']=53; a['q']=59; a['r']=61; a['s']=67;
a['t']=71; a['u']=73; a['v']=79;
a['w']=83; a['x']=89; a['y']=97; a['z']=101;
int[] nums = new int[strs.length];
HashMap<Long, List<String>> hashmap = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
long result = 2;
for (int j = 0; j < strs[i].length(); j++) {
result *= a[strs[i].charAt(j)];
}
if (hashmap.containsKey(result)) {
List<String> list = hashmap.get(result);
list.add(strs[i]);
hashmap.put(result, list);
} else {
List<String> list = new ArrayList<>();
list.add(strs[i]);
hashmap.put(result, list);
}
}
List<List<String>> solut = new ArrayList<>();
for (List<String> value : hashmap.values()) {
solut.add(value);
}
return solut;
}
}