LeetCode49 字母异位分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
思路
用哈希表进行分类,把String转化为char数组再排序作为key,value为一个List,通过拉链法存放同类的String。
主要还是考察哈希表的运用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap <String,ArrayList<String>>map=new HashMap<>(); for(String s:strs){ char []ch=s.toCharArray(); Arrays.sort(ch); String key=String.valueOf(ch); if(!map.containsKey(key)){ map.put(key,new ArrayList<>()); } map.get(key).add(s); } return new ArrayList(map.values()); } }
最后
以上就是难过画笔最近收集整理的关于LeetCode49 字母异位分组LeetCode49 字母异位分组的全部内容,更多相关LeetCode49内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复