Skip to content

Instantly share code, notes, and snippets.

@aquawj
Created December 16, 2017 00:37
Show Gist options
  • Save aquawj/4e620c059e4522bebfb65e9a5f7b6af6 to your computer and use it in GitHub Desktop.
Save aquawj/4e620c059e4522bebfb65e9a5f7b6af6 to your computer and use it in GitHub Desktop.
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
思路:
1.map<String, List<String>>,key是排过序的String, List是相同的anagram
2. 比较是否anagram,只需要把每个String转成charArray再排序
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if(strs == null || strs.length == 0){
return res;
}
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs){
char[] chars = str.toCharArray();
Arrays.sort(chars);
String s = new String(chars);
if(!map.containsKey(s)){
map.put(s, new ArrayList<String>());
}
map.get(s).add(str);
}
res.addAll(map.values());
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment