Created
December 26, 2012 04:54
-
-
Save zac-xin/4377963 to your computer and use it in GitHub Desktop.
Given an array of strings, return all groups of strings that are anagrams.
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 class Solution { | |
public ArrayList<String> anagrams(String[] strs) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); | |
ArrayList<String> result = new ArrayList<String>(); | |
if(strs.length < 2) | |
return result; | |
for(int i = 0 ; i < strs.length; i++){ | |
String s = strs[i]; | |
char arr[] = s.toCharArray(); | |
Arrays.sort(arr); | |
String t = new String(arr); | |
if(!map.containsKey(t)){ | |
ArrayList<String> list = new ArrayList<String>(); | |
list.add(s); | |
map.put(t, list); | |
}else{ | |
map.get(t).add(s); | |
} | |
} | |
for(String str : map.keySet()){ | |
if(map.get(str).size() > 1){ | |
for(String v : map.get(str)){ | |
result.add(v); | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment