I've been trying to solve this problem from leetcode that says:
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Here's a solution I came up with:
class Solution {
public List<List<String>> groupAnagrams(String[] strs)
{
List<List<String>> result=new ArrayList<>();
Map<String, ArrayList<String>> map=new HashMap<>();
for(String s: strs)
{
if(map.containsKey(sortAlphabetically(s))==false)
{
map.put(sortAlphabetically(s), new ArrayList<>());
}
else
{
map.get(sortAlphabetically(s)).add(s);
}
}
for(String key:map.keySet())
{
result.add(map.get(key));
}
return result;
}
public String sortAlphabetically(String s)
{
char[] s2=s.toCharArray();
Arrays.sort(s2);
return new String(s2);
}
}
But when I try to run it it says that the output is wrong. What can I improve?
Change
if(map.containsKey(sortAlphabetically(s))==false)
{
map.put(sortAlphabetically(s), new ArrayList<>());
}
else
{
map.get(sortAlphabetically(s)).add(s);
}
to
if (!map.containsKey(sortAlphabetically(s))) {
map.put(sortAlphabetically(s), new ArrayList<>());
}
map.get(sortAlphabetically(s)).add(s);
You forgot to add the String
to the List
of a new key in your Map
.
PS, perhaps you should call sortAlphabetically(s)
just one time, and store the result in a variable. It will improve performance.
String sorted = sortAlphabetically(s);
if (!map.containsKey(sorted)) {
map.put(sorted, new ArrayList<>());
}
map.get(sorted).add(s);
Also note that this solution is case sensitive. ie "Sad" is not an anagram of "ads".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.