题目描述:
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。
解析:
1.检查是否为空数组
2.遍历所有字符串,然后建立一个长度为26的数组,起始值为0。
将字母出现的频率放到数组的对应位置里(利用ascii码)
3.遍历数组,按照相同字母出现频率进行分组归类(使用hashmap)
4.遍历map,将结果返回
Java:
public List<List<String>> groupAnagrams(String[] strs) {
if(strs.length == 0) {
return new ArrayList();
}
HashMap<String, List> map = new HashMap<String, List>();
int[] characters = new int[26];
for(String str : strs) {
Arrays.fill(characters, 0);
for(int i = 0; i < str.length(); i++) {
int ascii = str.charAt(i) - 97;
characters[ascii]++;
}
StringBuilder sb = new StringBuilder("");
for(int i = 0; i < 26;i++) {
sb.append(characters[i]);
}
String key = sb.toString();
if(!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);
}
return new ArrayList(map.values());
}JavaScript:
var groupAnagrams = function(strs) {
if(strs.length === 0) {
return [];
}
const map = new Map();
for(const str of strs) {
const characters = Array(26).fill(0);
for(let i = 0; i < str.length; i++) {
const ascii = str.charCodeAt(i) - 97;
characters[ascii]++;
}
const key = characters.join("");
if(map.has(key)) {
map.set(key, [...map.get(key), str]);
} else {
map.set(key, [str]);
}
}
const result = [];
for(const arr of map) {
result.push(arr[1]);
}
return result;
};
京公网安备 11010502036488号