Topic description
Given an array of strings, group anagrams together. Alphabetical anagrams are strings of the same letters but different arrangements.
enter:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"], output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]Instructions:
1. All inputs are in lowercase letters.
2. The order in which the answers are output is not considered.
Problem solving ideas
1.新建,Map<String,List<String>>
2. Iterate over each string in the string array
Take each string ---> character array and sort it
Sorted character array -- "string, as key, to find and add to Map<String,List<String>>
3. Finally, output all the values in Map<String,List<String>>
public List<List<String>> groupAnagrams(String[] strs) { if (strs == null || strs.length == 0) return new ArrayList<List<String>>(); Map<String,List<String>> map = new HashMap<String, List<String>>(); for (String s:strs){ char[] ca = s.toCharArray(); Arrays.sort(ca); //sort from small to large String keyStr = String.valueOf(ca); if (!map.containsKey(keyStr)){ map.put(keyStr,new ArrayList<String>()); } map.get(keyStr).add(s); } return new ArrayList<List<String>>(map.values()); }