leetcode-567 字符串的排列

题目描述:给你两个字符串 s1s2 ,写一个函数来判断 s2 是否包含 s1 的排列。

换句话说,s1 的排列之一是 s2子串

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public boolean checkInclusion(String s1, String s2) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
need.merge(s1.charAt(i), 1, (oldVal, newVal) -> ++oldVal);
}

int left = 0, right = 0, valid = 0;
while (right < s2.length()) {
char r = s2.charAt(right);
right++;
if (need.containsKey(r)) {
window.merge(r, 1, (oldVal, newVal) -> ++oldVal);
if (window.get(r).equals(need.get(r))) {
valid++;
}
}

while (right - left == s1.length()) {
if (valid == need.size()) {
return true;
}
char l = s2.charAt(left);
left++;
if (need.containsKey(l)) {
if (window.get(l).equals(need.get(l))) {
valid--;
}
window.compute(l, (k, v) -> --v);
}
}
}
return false;
}
}