題目地址:
https://www.lintcode.com/problem/group-anagrams/description
給定一個字符串數組,將其按照anagram分類返回。anagram意思是,字母相同並且每個字母出現次數也相同。
可以將每個字符串內的字符排序,這樣每個anagram內的字符串都會對應唯一的一個key,再用一個哈希表記錄每個key對應哪些字符串即可。代碼如下:
import java.util.*;
public class Solution {
/**
* @param strs: the given array of strings
* @return: The anagrams which have been divided into groups
*/
public List<List<String>> groupAnagrams(String[] strs) {
// write your code here
List<List<String>> res = new ArrayList<>();
if (strs == null || strs.length == 0) {
return res;
}
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] s = strs[i].toCharArray();
Arrays.sort(s);
String key = new String(s);
map.putIfAbsent(key, new ArrayList<>());
map.get(key).add(strs[i]);
}
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
res.add(entry.getValue());
}
return res;
}
}
時間複雜度,空間。