49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Constraints:
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
Example
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
思路
做这题前先去做217. Contains Duplicate [Easy]
,有了这题的基础后,很自然就能联想到这些Anagrams他们经过排序后,一定会相同,拿这个作为他们的key来区分就行了
题解
public List<List<String>> groupAnagrams(String[] strs) {
// key就是经过排序后的anagram,value就来存结果
HashMap<String, List<String>> result = new HashMap<>();
for (String val : strs) {
char[] keyChar = val.toCharArray();
Arrays.sort(keyChar);
// 拿到经过排序后的key
String key = String.valueOf(keyChar);
// 去Map里找有没有这个key,没有的话他就是第一个,new一个List,把它放进去
if (!result.containsKey(key))
result.put(key, new ArrayList<>(Arrays.asList(val)));
else {
// 有的话就往里面塞
result.get(key).add(val);
}
}
// 转换成期望的格式
return result.values().stream().collect(Collectors.toList());
}
标签:Medium,Group,val,Anagrams,strs,result,key,String
From: https://www.cnblogs.com/tanhaoo/p/17036916.html