class Solution {
public boolean checkInclusion(String s1, String s2) {
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> window = new HashMap<>();
for(char c : s1.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;
while (right < s2.length()) {
// 将移入窗口的字符
char c = s2.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 >= s1.length()) {
// 判断是否找到满足条件的子串
if (count == need.size()) {
return true;
}
// 将移出窗口的字符
char b = s2.charAt(left);
// 左移窗口
left++;
// 更新窗口内数据
if (need.containsKey(b)) {
if (need.get(b).equals(window.get(b))) {
count--;
}
window.put(b, window.get(b) - 1);
}
}
}
return false;
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交