网站不做备案,邢台168,桂林生活论坛网,想开个网站建设的公司Hot100 - 字母异位词分组 最佳思路#xff1a;排序
时间复杂度#xff1a; O(nmlogm)#xff0c;其中 n 为 strs 数组的长度#xff0c;m 为每个字符串的长度。
代码#xff1a;
class Solution {public ListListString groupAnagrams(String[] strs) …Hot100 - 字母异位词分组 最佳思路排序
时间复杂度 O(nmlogm)其中 n 为 strs 数组的长度m 为每个字符串的长度。
代码
class Solution {public ListListString groupAnagrams(String[] strs) {MapString, ListString map new HashMap();for (String str : strs) {char[] s str.toCharArray();Arrays.sort(s); // 对字母排序String sortedStr new String(s); // 排序后的字符串作为keymap.computeIfAbsent(sortedStr, k - new ArrayList()).add(str);}return new ArrayList(map.values());}
}思路
排序每个字符串首先对每个字符串的字母进行排序排序后的结果作为唯一标识符key。使用 Map 存储将排序后的字符串作为 key原始字符串作为值存入 Map。使用 computeIfAbsent 方法可以简化代码避免多次检查和更新 Map。最终返回 Map 中所有的字母异位词组。