leetcode-Group Anagrams
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case;
映射关系如下:
代码如下:
package leetcode;
import java.util.*;
import java.util.Map.Entry;
//思路:建立一个map映射关系,先对string排好序 -> 作为键 ,然后将map的value映射到List里面去~
//list的优点:可变!
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] ers = str.toCharArray();
Arrays.sort(ers);
String keyStr = String.valueOf(ers);
if (!map.containsKey(keyStr))
map.put(keyStr, new ArrayList<>()); //value就是新的list,然后加入原来的str
map.get(keyStr).add(str); //如果不是新的list,那么直接加入str
}
for (Entry<String, List<String>> entry : map.entrySet()) { //map的Entry是一个set,不重复,因为不同的entry,hashcode不同
//确保其唯一性
List<String> newvalues = entry.getValue();
Collections.sort(newvalues); //这里,map的key是一个set,而value是一个list,所以可以排序;
ans.add(newvalues);
}
return ans;
}
}