一 题目
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
二 分析
medium 级别,求错位词 分组,所谓的错位词就是两个字符串中字母出现的次数都一样,只是位置不同。(都是小写)错位词分在一组。只要排序后,错位词就是一致的。常规聚会想到hashmap,key 是字符串,value:list<String>.
所以排序是必要的,不然ate,tea这种分不到一组。
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList();
//coner case
if(strs == null|| strs.length==0){
return res;
}
Map<String, List<String>> map = new HashMap<>();
for(int i=0;i< strs.length;i++){
String str = strs[i];
char[] cs =str.toCharArray();
Arrays.sort(cs);
String tmp = new String(cs);
if(!map.containsKey(tmp)){
List<String> list = new ArrayList<String>();
list.add(str);
map.put(tmp, list);
}else{
map.get(tmp).add(str);
}
}
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.getValue().size() >= 1) {
res.add(entry.getValue());
}
}
return res;
}
Runtime: 9 ms, faster than 80.87% of Java online submissions for Group Anagrams.
Memory Usage: 41.4 MB, less than 94.74% of Java online submissions for Group Anagrams.
时间复杂度:O(N*nlgn)
要是不用排序。用字符+对应出现次数如:a1b2c3,来替代。
public static List<List<String>> groupAnagrams(String[] strs) {
String[] letter= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
List<List<String>> res = new ArrayList();
//coner case
if(strs == null|| strs.length==0){
return res;
}
Map<String, List<String>> map = new HashMap<>();
for(int i=0;i< strs.length;i++){
String str = strs[i];
char[] cs =str.toCharArray();
int[] ids = new int[26];
for(char c:cs){
ids[c-'a']++;
}
String tmp = "";
for(int j=0;j<26;j++){
if(ids[j]>0){
tmp += letter[j]+ids[j];
}
}
if(!map.containsKey(tmp)){
List<String> list = new ArrayList<String>();
list.add(str);
map.put(tmp, list);
}else{
map.get(tmp).add(str);
}
}
for(String key : map.keySet()) {
List<String> list = map.get(key);
res.add(list);
}
return res;
}
得处理两遍,写的不好,比上一个效率还低。15 ms 了。