vault backup: 2022-07-14 11:03:17

This commit is contained in:
juan 2022-07-14 11:03:17 +08:00
parent 775b43b58b
commit 3719fb0a11

View file

@ -53,6 +53,47 @@ In other words, return `true` if one of `s1`'s permutations is the substring of
I tried to use kadane's algorithm, but the problem is a premature string, not set. So I gave up.
Then I found out this is sliding window problem, similar to
[[Leetcode Longest-Substring-Without-Repeating-Characters]]
### Solution
```cpp
class Solution {
public:
bool checkInclusion(string s1, string s2) {
// Sliding windows problem.
// First, register the freqs of s1
vector<int> freq(26, 0);
for (char ch : s1) {
freq[ch - 'a']++;
}
// Second, start constructing window and window freq;
int len = s1.length();
int l = 0, r = 0;
vector<int> window(26, 0);
// Start expanding and sliding!
while (r < s2.length()) {
// I add value to window here, to avoid r OOB when r = s2.length
window[s2[r] - 'a']++;
if (r - l + 1 < len) {
// Expand right
r++;
} else if (window == freq) { // note that I use else if, to make sure
// every time r is incremented once.
return true;
} else {
// Remove l from the window, slide right
window[s2[l] - 'a']--;
l++;
r++;
}
}
return false;
}
};
```