Java 题解 | #牛棚品种分类#
牛棚品种分类
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 if (strs == null || strs.length == 0) { return new String[0]; } Map<String, List<String>> map = new HashMap<>(); for (String str : strs) { char[] chars = str.toCharArray(); Arrays.sort(chars); String key = new String(chars); if (!map.containsKey(key)) { map.put(key, new ArrayList<>()); } map.get(key).add(str); } List<String> resultList = new ArrayList<>(); for (List<String> list : map.values()) { StringBuilder sb = new StringBuilder(); for (String str : list) { sb.append(str).append(","); } sb.deleteCharAt(sb.length() - 1); resultList.add(sb.toString()); } Collections.sort(resultList); return resultList.toArray(new String[0]); } }
该题考察的主要知识点是字符串处理和哈希表的运用。
代码的文字解释如下:
- 创建一个空的哈希表
map
,用于存储排序后的字符串作为键,以及相同键的单词列表作为值。 - 遍历输入的字符串数组
strs
。 - 对每个字符串进行字符排序,将排序后的字符串作为键。
- 如果哈希表中不存在该排序后的字符串作为键,则将其添加到哈希表,并将对应的值初始化为空列表。
- 将原始的字符串添加到该排序后的字符串对应的列表中。
- 完成遍历后,现在哈希表中每个键对应的值即为相同牛棚内的品种列表。
- 创建一个结果列表
resultList
,用于存储最终的结果。 - 遍历哈希表的所有值,即每个相同牛棚内的品种列表。
- 对于每个品种列表,使用一个字符串构建器
sb
来拼接所有的品种。 - 将拼接好的品种字符串添加到结果列表中。
- 对结果列表进行字典序排序。
- 将结果列表转换为字符串数组并返回。