I'm exceeding the time limit for a 10,000 word test case provided on LeetCode:
Given an array of strings, group anagrams together.
For example, given:
["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
Any suggestions on how I could speed this up a little bit?
public HashMap<String, List<Integer>> createMap(String[] strs)
{
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
for(String s: strs)
{
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
if(map.containsKey(sortedString))
{
List<Integer> pos = map.get(sortedString);
pos.add(Arrays.asList(strs).indexOf(s));
map.put(sortedString, pos);
}
else
{
List<Integer> pos = new ArrayList<Integer>();
pos.add(Arrays.asList(strs).indexOf(s));
map.put(sortedString, pos);
}
}
return map;
}
public List<List<String>> groupAnagrams(String[] strs) {
HashMap hm = createMap(strs);
List<List<String>> anagrams = new ArrayList<List<String>>();
for(Object k: hm.keySet())
{
String key = k.toString();
ArrayList pos = (ArrayList)hm.get(key);
List<String> a = new ArrayList<String>();
for(Object p : pos)
{
int idx = Integer.parseInt(p.toString());
a.add(strs[idx]);
}
anagrams.add(a);
}
return anagrams;
}