算法之旅-Hot100—字母异位词分组
题目:字母异位词分组
描述:给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
示例:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]] 解释: 在 strs 中没有字符串可以通过重新排列来形成 "bat"。 字符串 "nat" 和 "tan" 是字母异位词,因为它们可以重新排列以形成彼此。 字符串 "ate" ,"eat" 和 "tea" 是字母异位词,因为它们可以重新排列以形成彼此。算法思路:
将每个字符串重新排序然后判断是否有相同的,即为异位词,通过 HashMap 存储,Key 存储重新排序后的字符串,Value 存储一个 List 集合,里面包含全部的 Key 的异位词,最后获取HashMap中存储的全部集合。
**getOrDefault()**为获取 key 的 value,如果不存在则执行后面的操作。
class GroupAnagrams{ public List<List<String>> groupAnagrams(String[] strs){ HashMap<String,List<String>> hashMap = new HashMap<>(); for (String s : strs) { char[] array = s.toCharArray(); Arrays.sort(array); String key = new String(array); List<String> list = hashMap.getOrDefault(key, new ArrayList<String>()); list.add(key); hashMap.put(key,list); } return new ArrayList<>(hashMap.values()); } }注:只为记录自己的练习过程,方便回顾!
