Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
public class Solution { public ArrayList<String> anagrams(String[] strs) { // Start typing your Java solution below // DO NOT write main() function ArrayList<String> res = new ArrayList<String>(); HashMap<String,ArrayList<String>> list = new HashMap<String,ArrayList<String>>(); for(String str:strs){ char[] chars = str.toCharArray(); Arrays.sort(chars); String key = new String(chars);//change chars to string back to hashmap/arraylist if(list.containsKey(key)){ list.get(key).add(str);//through get(key) find position then add to existing list } else{ list.put(key, new ArrayList<String>(Arrays.asList(str))); } } for(ArrayList<String> temp:list.values()){ if(temp.size()>1){ res.addAll(temp); } } return res; } }
mistake: 1)list.put(key is the sorted string, value is new ArrayList<String>(Arrays.asList(str) 2) temp:list.values() sort list values
learned: hashMap key ==> value 这个value只能是一个,这个Value是一个ArrayList list.get(key).size()是个数