题目地址:
https://www.lintcode.com/problem/anagrams/description
给定一个字符串组成的数组,返回其中所有的anagram。anagram意思是含有相同字母并且每个字母出现相同次数。
可以用一个哈希表,key是字符串,value是字符串组成的list,每个字符串内部字符都进行排序,排序后得到的字符串作为key,这样key一样的字符串就属于同一个anagram,这样就可以将anagram加到同一个list里,最后累计返回即可。下面如下:
import java.util.*;
public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/
public List<String> anagrams(String[] strs) {
// write your code here
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++) {
// 算每个anagram对应的唯一的key
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()) {
if (entry.getValue().size() > 1) {
res.addAll(entry.getValue());
}
}
return res;
}
}
时间复杂度 O ( n l log l ) O(nl\log l) O(nllogl), n n n为字符串个数, l l l为最长字符串长度,空间 O ( n l ) O(nl) O(nl)。