Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Solution:
public ArrayList<String> anagrams(String[] strs) {
int len = strs.length;
HashMap<String, Integer> mymap = new HashMap<String, Integer>();
ArrayList<String> result = new ArrayList<String>();
for(int i=0;i<len;i++)
{
char[] cur = strs[i].toCharArray();
Arrays.sort(cur);
String sorted = new String(cur);
if(mymap.containsKey(sorted))
{
if(mymap.get(sorted)!=-1)
{
result.add(strs[mymap.get(sorted)]);
mymap.put(sorted,-1);
}
result.add(strs[i]);
}
else
{
mymap.put(sorted, i);
}
}
return result;
}
No comments:
Post a Comment