Question
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Stats
Frequency | 4 |
Difficulty | 3 |
Adjusted Difficulty | 4 |
Time to use | -------- |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Analysis
This is not an extremely difficult question, but I always get TLE error (Time limit exceeded), before I realize that I have to use HashMap.
Solution
The solution is making use of HashMap and sorting to check anagrams. For more, read this blog.
My code
public class Solution {
public List<String> anagrams(String[] strs) {
List<String> ans = new ArrayList<String>();
if (strs == null || strs.length == 0) {
return ans;
}
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for (String str: strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sorted = String.valueOf(chars);
if (!map.containsKey(sorted)) {
map.put(sorted, new ArrayList<String>());
}
map.get(sorted).add(str);
}
for (List<String> list: map.values()) {
if (list.size() > 1) {
ans.addAll(list);
}
}
return ans;
}
}