[面试题 10.02. 变位词组]:
链接 (https://leetcode-cn.com/problems/group-anagrams-lcci/)
编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。
注意:本题相对原题稍作修改
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
参考题解:
- 使用Hash 表来解决此问题
- 遍历 字符串, 将字符串 进行排序之后 作为键key
- key 对应 value 为 List 集合对象
- 循环遍历 str 并对其排序, 之后将其 加入 对应 key 的 List 中,若无对应key,默认创建 新的 List 集合
其中使用到 map 中方法:
getOrDefault() 方法:
获取指定 key 对应值 value,如果找不到 key ,则返回设置的默认值。
List<String> list = map.getOrDefault(key, new ArrayList<String>());
// 这里 要获取 指定key 对应的 list , 如果没有 该key, 默认创建新的 list对象
完整测试代码(参考力扣):
public class youngLiang01 {
public static void main(String[] args) {
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(groupAnagrams(strs));groupAnagrams(strs);
}
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String str : strs) {
char[] array = str.toCharArray(); // 字符串 转换为字符数组
Arrays.sort(array); // 排序
String key = new String(array);
List<String> list = map.getOrDefault(key, new ArrayList<String>());
// 若存在指定key,取出对应value(ArrayList集合),
//否则默认创建新的 集合
list.add(str); // 加入到 对应 list 集合中
map.put(key, list);
// 将 key(排序后的str)value(list集合) 加入到 map 中
}
return new ArrayList<List<String>>(map.values());
}
}
// 输出结果:[[eat, tea, ate], [bat], [tan, nat]]