Java后端
·2025-02-16leetcode hot 100 * 1 ,49中等字母异位词分组,思路简单,每个字符排序后相同即为异位分组词。
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if (strs.length < 1)
return res;
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
String sortedStr = sort(strs[i]);
if (map.containsKey(sortedStr)) {
map.get(sortedStr).add(strs[i]);
} else {
List<String> t = new ArrayList<>();
t.add(strs[i]);
map.put(sortedStr, t);
res.add(t);
}
}
return res;
}
public String sort(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
StringBuilder sb = new StringBuilder();
for (char c : chars) {
sb.append(c);
}
return sb.toString();
}
leetcode hot 100 * 1 ,438找到字符串找那个所有字母异位词。返回子串的起始索引,这个想着循环遍历,排序每个字符串匹配,时间复杂度n*n,最终暴力超时。优化方式,通过滑动窗口+数组统计,字符串a-z一共26位,定义定长26数组,保存每个字符出现频率。遍历字符串,将窗口固定为要匹配的字符串长度,匹配成功左窗口索引加入结果中。
List<Integer> res = new ArrayList<>();
// a-z
int[] pCount = new int[26];
int[] sCount = new int[26];
for(int i=0;i<p.length();i++){ // 统计p字母
pCount[p.charAt(i)-'a']++;
}
for(int right=0;right<s.length();right++){
sCount[s.charAt(right)-'a']++; // 统计当前字符
int left = right - p.length() + 1; // 固定窗口
if(left < 0) continue; // 跳过窗口不满足长度
if(Arrays.equals(pCount,sCount)){
res.add(left);
}
sCount[s.charAt(left) - 'a']--; //移除字符--> 窗口左端右移
}
return res;
}
牛客acm模式刷题 * 5 ,简单题不做记录,全是api操作。
软考机操知识点复习完毕。继续come on。
继续rpc。
八股文啊八股文,什么时候你能完全到我脑子里。
3
0
分享
操作
评论
问答助学
相关内容
0个评论
全部评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
