class Solution {
public List<Integer> findAnagrams(String s, String p) {
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> window = new HashMap<>();
for(char c : p.toCharArray()) {
if(need.containsKey(c)) {
need.put(c, need.get(c) + 1);
} else {
need.put(c, 1);
}
}
int left = 0;
int right = 0;
int count = 0;
List<Integer> ans = new ArrayList<>();
while (right < s.length()) {
// 将移入窗口的字符
char c = s.charAt(right);
// 右移窗口
right++;
// 更新窗口内数据
if (need.containsKey(c)) {
if (window.containsKey(c)) {
window.put(c, window.get(c) + 1);
} else {
window.put(c, 1);
}
if (window.get(c).equals(need.get(c))) {
count++;
}
}
// 收缩窗口
while (right - left >= p.length()) {
// 判断是否找到满足条件的子串
if (count == need.size()) {
ans.add(left);
}
// 将移出窗口的字符
char b = s.charAt(left);
// 左移窗口
left++;
// 更新窗口内数据
if (need.containsKey(b)) {
if (need.get(b).equals(window.get(b))) {
count--;
}
window.put(b, window.get(b) - 1);
}
}
}
return ans;
}
}
leetcode-438-找到字符串中所有字母异位词
最新推荐文章于 2022-03-01 11:44:02 发布