- Permutation in String
Medium
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1’s permutations is the substring of s2.
Example 1:
Input: s1 = “ab”, s2 = “eidbaooo”
Output: true
Explanation: s2 contains one permutation of s1 (“ba”).
Example 2:
Input: s1 = “ab”, s2 = “eidboaoo”
Output: false
Constraints:
1 <= s1.length, s2.length <= 104
s1 and s2 consist of lowercase English letters.
解法1:滑动窗口。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int len1 = s1.size(), len2 = s2.size();
vector<int> need(26, 0), actual(26, 0);
int needCount = 0;
for (int i = 0; i < len1; i++) {
if (need[s1[i] - 'a'] == 0) needCount++;
need[s1[i] - 'a']++;
}
int p1 = 0, p2 = 0;
int validCount = 0;
while (p2 < len2) {
char c = s2[p2];
if (need[c - 'a'] > 0) {
actual[c - 'a']++;
if (actual[c - 'a'] == need[c - 'a']) validCount++;
}
p2++;
while (validCount == needCount) {
int len = p2 - p1;
if (len == len1) return true;
if (len > len1) { //move left pointer
c = s2[p1];
if (need[c - 'a'] > 0) {
if (actual[c - 'a'] == need[c - 'a']) {
validCount--;
}
actual[c - 'a']--;
}
p1++;
}
}
}
return false;
}
};