49.字母异位词分组

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        // 创建哈希表,键为排序后的特征字符串,值为对应的异位词分组
        Map<String, List<String>> map = new HashMap<>();
        
        // 遍历输入数组中的所有字符串
        for (String s : strs) {
            // 将字符串转换为字符数组以便排序
            char[] chars = s.toCharArray();
            
            // 对字符数组进行排序:异位词排序后会得到相同的字符序列
            Arrays.sort(chars);
            
            // 将排序后的字符数组转换为字符串作为特征键
            String sortedStr = new String(chars);

            // 如果当前特征键不存在,创建新的分组列表
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            
            // 将原始字符串添加到对应分组
            map.get(sortedStr).add(s);
        }

        // 将哈希表的值集合转换为ArrayList返回(所有分组结果)
        return new ArrayList<>(map.values());
    }
}
posted @ 2025-05-20 17:47  星星永远发着光  阅读(11)  评论(0)    收藏  举报