1. 题目来源
链接:3768. 字符串删减
2. 题目解析
模拟。
线性扫描即可,cnt
记录连续 x
的数量,如果 cnt==3
说明连续 3 个需要删除末尾这个 x
,在此仅需 cnt--
即可。遇见非 x
字母,直接将 cnt=0
即可。
双指针也可,找到连续一段 xxx
,删成 2 个即可。
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
模拟+计数
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int res = 0, cnt = 0;
for (char &c : s) {
if (c == 'x') {
cnt ++ ;
if (cnt == 3) {
res ++ ;
cnt -- ;
}
} else cnt = 0;
}
cout << res << endl;
return 0;
}
双指针
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int res = 0, cnt = 0;
for (int i = 0; i < n; i ++ ) {
if (s[i] != 'x') continue;
int j = i + 1;
while (j < s.size() && s[j] == 'x') j ++ ;
res += max(0, j - i - 2);
i = j - 1;
}
cout << res << endl;
return 0;
}
STL
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int res = 0;
while (s.find("xxx") != -1) {
s.erase(s.begin() + s.find("xxx") + 2);
res ++ ;
}
cout << res << endl;
return 0;
}