算法 -- 字母异位词分组
程序员文章站
2022-03-07 11:27:38
LeetCode刷题记7149. 字母异位词分组题目class Solution { public List
- > groupAnagrams(String[] strs) { List
- > ans = new ArrayList(); Map
LeetCode刷题记71
49. 字母异位词分组
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList();
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (int i = 0; i < strs.length; i ++) {
int[] nums = new int[26];
for (int j = 0; j < strs[i].length(); j ++) {
nums[strs[i].charAt(j) - 'a'] ++;
}
String s = "";
for (int j = 0; j < 26; j ++) {
s += nums[j] + ".";
}
System.out.println(s);
if (map.containsKey(s)) {
List<String> tmp = map.get(s);
tmp.add(strs[i]);
map.put(s, tmp);
} else {
List<String> tmp = new ArrayList<String>();
tmp.add(strs[i]);
map.put(s, tmp);
}
}
for (List<String> list : map.values()) {
ans.add(list);
}
return ans;
}
}
关键是找一个hash算法将字符串映射
3/5
71/150
本文地址:https://blog.csdn.net/weixin_44013557/article/details/110259342
上一篇: angularjs实现的前端分页控件示例