772 · Group Anagrams - LintCode

# Description

To give you a string array, please group the misplaced words(refers to the same character string with different permutations).

All input are lower case

# Example

Example 1:

Input:
["eat","tea","tan","ate","nat","bat"]
Output:
[["ate","eat","tea"],
 ["bat"],
 ["nat","tan"]]
 

Example 2:

Input:
["eat","nowhere"]
Output:
[["eat"],
 ["nowhere"]]

# code

這一題用到 171 的概念 Lintcode 171-Anagrams - Algorithm - Java - Computer Science | Tiffany Iong = Sleep more zzzZ..... = 努力也許會說謊,但是不會白費

相同的是:還是一樣 要把字符串排序放在 hashMap 裡
不同的是:這次把所有的字符都分組,把 anagram 放在一起,不同的字符都分開放。

# version1

要注意的是怎麼分組...

hm.put(sortedStr, index++);
res.add(new ArrayList<String>());
res.get(hm.get(sortedStr)).add(s);
public List<List<String>> groupAnagram(String[] strs) {
	List<List<String>> res = new ArrayList<List<String>>();
	Map<String, Integer> hm = new HashMap<>();
	int index = 0; //res 的位置 
	for (String s : strs) {
		char[] charArray = s.toCharArray();
		Arrays.sort(charArray);
		String sortedStr = String.valueOf(charArray);
		if (!hm.containsKey(sortedStr)) {
			hm.put(sortedStr, index++);
			res.add(new ArrayList<String>());
		} 
		res.get(hm.get(sortedStr)).add(s);
	}
	return res;
}

# version 2

hm.putIfAbsent(sortedArr, new ArrayList<>());
hm.get(sortedArr).add(s);
return new Arraylist<>(hm.values());
public List<List<String>> groupAnagrams(String[] strs) {
	Map<String, List<String>> hm = new HashMap<>();
	for (String s: strs) {
		char[] charArr = s.toCharArray();
		Arrays.sort(charArr);
		String sortedArr = String.valueOf(charArr);
		hm.putIfAbsent(sortedArr, new ArrayList<>());
		hm.get(sortedArr).add(s);
	}
	return new Arraylist<>(hm.values());
}