Created
December 16, 2017 00:37
-
-
Save aquawj/4e620c059e4522bebfb65e9a5f7b6af6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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