Given two strings s and p, find the substrings of all anagrams of p in s and return the starting index of these substrings. The order of answer output is not taken into account.
Anagrams refer to strings with the same letters but different arrangements.
Example 1 :
输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的变位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的变位词。
Example 2 :
输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的变位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的变位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的变位词。
Tips :
1 <= s.length, p.length <= 3 * 104
s 和 p 仅包含小写字母
answer
sliding window
- left and right mark the window, the left is closed and the right is open
[left, right)
. - need marks the required number of each character, win marks the number of characters in the window
- valid is used to mark the number of valid characters in the window. valid + 1 only when the number of characters A in the window is exactly equal to the required number of characters A
- When valid is equal to the required number (
need.size
), and the window size (right - left
) is equal to the required number of characters, add left to the result set
#include "bits/stdc++.h"
using namespace std;
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
map<char, int> need, win;
for (auto ch : p) {
++need[ch];
}
int left = 0;
int right = 0;
int valid = 0;
while (right < s.size()) {
// 需要增加窗口
char ch = s[right];
++right;
if (need.count(ch) != 0) {
// 用"need[ch] != 0"会使得need的size+1
++win[ch];
if (win[ch] == need[ch]) {
++valid;
}
} else {
left = right;
valid = 0;
win.clear();
}
// 需要收缩窗口
while (valid == need.size()) {
if (right - left == p.size()) {
res.push_back(left);
}
ch = s[left];
++left;
--win[ch];
if (win[ch] < need[ch]) {
// 不要用"!=",也不要用"win[ch] == 0"
--valid;
}
}
}
return res;
}
};
Sliding window template description: https://labuladong.github.io/algo/2/19/26/