删了键之后呢
同样的滑动,这次减到 0 就 erase 掉。运行它:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
void add_ch(map<char, int>& cnt, char ch) {
cnt[ch]++;
}
void drop_ch(map<char, int>& cnt, char ch) {
cnt[ch]--;
if (cnt[ch] == 0) cnt.erase(ch);
}
int main() {
map<char, int> cnt;
string s = "abcabcbb";
int k = 3;
for (int i = 0; i < k; i++) add_ch(cnt, s[i]);
for (int i = k; i < (int)s.size(); i++) {
add_ch(cnt, s[i]);
drop_ch(cnt, s[i - k]);
}
cout << cnt.size() << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)