[LeetCode Hot 100] LeetCode438. 找到字符串中所有字母异位词
题目描述
思路:滑动窗口模板
- 需要维护的变量:
// 1. 用于存放结果
List<Integer> res = new ArrayList<>();
// 2. 定义需要维护的变量:根据题意可知是一个哈希表
Map<Character, Integer> map = new HashMap<>();
Map<Character, Integer> hashmap_p = new HashMap<>();
for (char ch : p.toCharArray()) {
hashmap_p.put(ch, hashmap_p.getOrDefault(ch, 0) + 1);
}
- 窗口长度为固定,所以用if:
if (end >= p.length() - 1) {
// 或者 if (end - start + 1 == p.length()) {}
char startChar = s.charAt(start);
map.put(startChar, map.get(startChar) - 1);
if (map.get(startChar) == 0) {
map.remove(startChar);
}
start ++;
}
类似LeetCode643. 子数组最大平均数I
方法一:滑动窗口
class Solution {
public List<Integer> findAnagrams(String s, String p) {
// 1. 用于存放结果
List<Integer> res = new ArrayList<>();
// 2. 定义需要维护的变量:根据题意可知是一个哈希表
Map<Character, Integer> map = new HashMap<>();
Map<Character, Integer> hashmap_p = new HashMap<>();
for (char ch : p.toCharArray()) {
hashmap_p.put(ch, hashmap_p.getOrDefault(ch, 0) + 1);
}
// 3. 定义窗口区间范围
int start = 0;
for (int end = 0; end < s.length(); end ++) {
// 4. 更新需要维护的变量
char currentChar = s.charAt(end);
map.put(currentChar, map.getOrDefault(currentChar, 0) + 1);
if (map.equals(hashmap_p)) {
res.add(start);
}
// 5. 由题意知:窗口固定用if
if (end >= p.length() - 1) {
char startChar = s.charAt(start);
map.put(startChar, map.get(startChar) - 1);
if (map.get(startChar) == 0) {
map.remove(startChar);
}
start ++;
}
}
return res;
}
}
方法二:跟方法一在最后一个if中处理不同
class Solution {
public List<Integer> findAnagrams(String s, String p) {
// 1. 用于存放结果
List<Integer> res = new ArrayList<>();
// 2. 定义需要维护的变量:根据题意可知是一个哈希表
Map<Character, Integer> map = new HashMap<>();
Map<Character, Integer> hashmap_p = new HashMap<>();
for (char ch : p.toCharArray()) {
hashmap_p.put(ch, hashmap_p.getOrDefault(ch, 0) + 1);
}
// 3. 定义窗口区间范围
int start = 0;
for (int end = 0; end < s.length(); end ++) {
// 4. 更新需要维护的变量
char currentChar = s.charAt(end);
map.put(currentChar, map.getOrDefault(currentChar, 0) + 1);
if (map.equals(hashmap_p)) {
res.add(start);
}
// 5. 由题意知:窗口固定用if
if (end - start + 1 == p.length()) {
char startChar = s.charAt(start);
map.put(startChar, map.get(startChar) - 1);
if (map.get(startChar) == 0) {
map.remove(startChar);
}
start ++;
}
}
return res;
}
}
本文作者:Ac_c0mpany丶
本文链接:https://www.cnblogs.com/keyongkang/p/17874895.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步