题解 | #牛棚品种分类#
牛棚品种分类
https://www.nowcoder.com/practice/0b6068f804b9426aa737ea8606e8d5c3
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param strs string字符串一维数组
* @return string字符串一维数组
*/
public String[] groupAnagrams (String[] strs) {
// write code here
// 创建一个HashMap用于存储相同字母组成的牛棚品种
HashMap<String, List<String>> map = new HashMap<>();
// 遍历每个牛棚品种
for (String str : strs) {
// 将品种字符串转换为字符数组,并进行排序
char[] chars = str.toCharArray();
Arrays.sort(chars);
// 将排序后的字符数组转换为字符串
String sortedStr = new String(chars);
// 如果map中不存在该字符串,则创建一个新的列表存储该字符串对应的牛棚品种
if (!map.containsKey(sortedStr)) {
map.put(sortedStr, new ArrayList<>());
}
// 将当前品种添加到对应的牛棚品种列表中
map.get(sortedStr).add(str);
}
// 创建结果列表
List<String> result = new ArrayList<>();
// 遍历HashMap中的所有牛棚品种,按照字典序将牛棚内的品种以逗号隔开
for (List<String> list : map.values()) {
String combinedStr = String.join(",", list);
result.add(combinedStr);
}
Collections.sort(result);
// 将列表转换为数组并返回
return result.toArray(new String[0]);
}
}
Java代码
考察的知识点包括Map、字符串转换字符数组、排序等
- 创建一个HashMap,用于存储相同字母组成的牛棚品种。
- 遍历每个牛棚品种,将品种字符串转换为字符数组,并对字符数组进行排序。
- 将排序后的字符数组转换为字符串sortedStr。
- 如果map中不存在sortedStr,则创建一个新的空列表,用于存储该字符串对应的牛棚品种。
- 将当前品种添加到对应的牛棚品种列表中。
- 创建结果列表result。
- 遍历map中的所有牛棚品种,按照字典序将牛棚内的品种以逗号隔开,并添加到result中,然后result排序。
- 将result列表转换为数组并返回。
