Given an array of strings, group anagrams together.
For example, given: "eat", "tea", "tan", "ate", "nat", "bat",
Return:
[
"ate", "eat","tea",
"nat","tan",
"bat"
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<List<String>>();
}
List<List<String>> rt = new ArrayList<List<String>>();
Map<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
// 把单词分组
for (int i = 0; i < strs.length; i++) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String k = Arrays.toString(c);
ArrayList<Integer> list = new ArrayList<Integer>();
if (map.containsKey(k)) {
list = map.get(k);
}
list.add(i);
map.put(k, list);
}
for (String s : map.keySet()) {
List<Integer> l = map.get(s);
List<String> group = new ArrayList<String>();
// 把相同字母的单词放入同一个list
for (Integer i : l) {
group.add(strs[i]);
}
// 按字典序排序
group.sort(new Comparator<String>() {
public int compare(String x, String y) {
return x.compareTo(y);
}
});
rt.add(group);
}
return rt;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有