题目说明
示例
示例1:
1 2 3 4 5 6 7
| 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
|
笔者理解
此题是一道哈希表算法问题,在力扣题库中被定义为中等题。
解法
当笔者阅读完此题后,发现此题采用哈希表进行记录比较容易求解,让我们来看看具体如何实现的吧。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution {
public List<List<String>> groupAnagrams(String[] strs) { HashMap<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) { char[] ch = strs[i].toCharArray(); Arrays.sort(ch); String s = new String(ch); List<String> temp; if (map.getOrDefault(s, null) == null) { temp = new ArrayList<>(); } else { temp = map.get(s); } temp.add(strs[i]); map.put(s, temp); }
List<List<String>> result = new ArrayList<>(); for(List<String> list : map.values()) { result.add(list); }
return result; } }
|
时间空间效率都还行,可见此解法还比较适合此题;

总结
本题是今天的每日一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。