法1:滑动窗口
Python
参考:灵茶山艾府
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
n = len(s1)
cnt1 = Counter(s1) # 子集
cnt2 = Counter()
left = 0
for right, x in enumerate(s2):
cnt2[x] += 1
if right - left + 1 == n:
if cnt2 == cnt1:
return True
cnt2[s2[left]] -= 1
left += 1
return False
Java
class Solution {
public boolean checkInclusion(String s1, String s2) {
int left = 0, right = 0, valid = 0;
int[] need = new int[256];
int[] window = new int[256];
Set<Character> usedSet = new HashSet<>();
for (Character c : s1.toCharArray()) {
need[c]++;
usedSet.add(c);
}
while (right < s2.length()) {
char curChar = s2.charAt(right);
right++;
if (need[curChar] > 0) {
window[curChar]++;
if (window[curChar] == need[curChar]) {
valid++;
}
}
while (right - left == s1.length()) {
if (valid == usedSet.size()) {
return true;
}
char deleteChar = s2.charAt(left);
left++;
if (window[deleteChar] > 0) {
if (window[deleteChar] == need[deleteChar]) {
valid--;
}
window[deleteChar]--;
}
}
}
return false;
}
}
557

被折叠的 条评论
为什么被折叠?



