Note: All inputs will be in lower-case.
Solution:
Use a HashMap to store sorted strings. If two strings are anagrams, they are the same after being sorted.
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
public ArrayList<String> anagrams(String[] strs) { | |
ArrayList<String> ret = new ArrayList<String>(); | |
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); | |
if(strs==null || strs.length == 0) return ret; | |
for(int i=0; i< strs.length; i++){ | |
char[] temp = strs[i].toCharArray(); | |
Arrays.sort(temp); | |
String sortedStr = new String(temp); | |
if(map.containsKey(sortedStr)){ | |
map.get(sortedStr).add(strs[i]); | |
} | |
else{ | |
ArrayList<String> newArr = new ArrayList<String>(); | |
newArr.add(strs[i]); | |
map.put(sortedStr, newArr); | |
} | |
} | |
for(ArrayList<String> arrs : map.values()){ | |
if(arrs.size()>1) | |
ret.addAll(arrs); | |
} | |
return ret; | |
} |
No comments:
Post a Comment