1、前言
题目描述2、思路
这道题也采用 567 题的滑动窗口思路,将每次能成功相等的窗口的起始位置都记录下来。
3、代码
class Solution {
public List<Integer> findAnagrams(String s, String p) {
if(s == null || s.length() == 0 || p == null || p.length() == 0){
return new ArrayList<>();
}
Map<Character, Integer> window = new HashMap<>();
Map<Character, Integer> need = new HashMap<>();
int m = s.length(), n = p.length();
if(m < n){
return new ArrayList<>();
}
for (char c : p.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}
for(int i = 0; i < n; i++){
window.put(s.charAt(i), window.getOrDefault(s.charAt(i), 0) + 1);
}
List<Integer> list = new ArrayList<>();
if(window.equals(need)){
list.add(0);
}
for(int i = n; i < m; i++){
char removeChar = s.charAt(i - n);
char addChar = s.charAt(i);
window.put(removeChar, window.get(removeChar) - 1);
if(window.get(removeChar) == 0){
window.remove(removeChar);
}
window.put(addChar, window.getOrDefault(addChar, 0) + 1);
if(window.equals(need)){
list.add(i - n + 1);
}
}
return list;
}
}
网友评论