算法 - 字母异位词分组

算法 - 字母异位词分组

题目:字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。

示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:

输入: strs = [""]
输出: [[""]]
示例 3:

输入: strs = ["a"]
输出: [["a"]]

提示:

1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> results = new ArrayList<>();
Map<String, Integer> mark = new HashMap<>();
for (String str : strs) {//迭代strs所有元素
char[] code = new char[26];
for (char c : str.toCharArray()) {
code[c - 'a']++;//记录每个字母出现次数
}
String key = new String(code);
List<String> result;
if (mark.containsKey(key)) {
result = results.get(mark.get(key));//hashmap中存在就拿该key在results的位置
}else {
result = new ArrayList<>();
mark.put(key, results.size());//存放该key在results的位置
results.add(result);
}
result.add(str);
}
return results;
}
}

本文作者:护发师兄

本文链接:https://www.cnblogs.com/jonil/p/15973744.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   护发师兄  阅读(27)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起