題目地址:
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;
}
}
時間複雜度,爲字符串個數,爲最長字符串長度,空間。