强迫症字符串:寻找最短的'zzz'子串
强迫症字符串:寻找最短的'zzz'子串
真真患上了强迫症,比如每天早上都要吃两个包子。真真发现他对字符串也有强迫症,他喜欢的字符串必须恰好包含3个'z'。
例如'poazdxzz'、'oixzzz'都是真真喜欢的字符串,我们称为真真串。但是像'yuzz'、'deoa'这样的字符串,真真是非常讨厌的。
现在给定一个只包含小写字母的字符串ch,请你帮助真真计算ch的所有子串中,最短的真真串是哪一个。
对于子串,我们规定:“xoi”、“itydre”都是“xoitydre”的子串,但是“xit”不是“xoitydre”的子串。
输入格式
输入一个只包含小写字母的字符串,字符串的长度不超过100000
输出格式
若输入的字符串的所有子串中有真真串,找到最短的真真串,输出其长度。若没有真真串,则输出“zzz”(不包含引号)。
样例 #1
样例输入 #1
happyzazziohell
样例输出 #1
4
样例 #2
样例输入 #2
xoizz
样例输出 #2
zzz
算法1
(暴力枚举) $O(n^2)$
枚举所有长度大于等于3的子串,计算其中是否存在3个z,若存在,更新答案。
时间复杂度
枚举子串的复杂度为$O(n^2)$,计算子串中有几个z的时间复杂度为$O(n)$,所以总的时间复杂度为$O(n^3)$。
算法2
(滑动窗口) $O(n)$
我们可以用两个指针l和r表示一个子串。初始时,l和r都指向字符串的开头。之后每次将r右移一位,判断l到r这个子串中是否恰好包含3个z。如果包含3个z,更新答案;如果不包含,将左指针l右移一位。这样,最终答案就是最短的包含3个z的子串。
时间复杂度
由于左指针和右指针最多各移动n次,所以总的时间复杂度为$O(n)$。
参考文献
王道考研机试指南
C++ 代码
算法1
#include <iostream>
#include <string>
using namespace std;
int main() {
string ch;
cin >> ch;
int n = ch.length();
int ans = -1;
for (int i = 0; i < n; i++) {
for (int j = i + 3; j <= n; j++) {
int cnt = 0;
for (int k = i; k < j; k++) {
if (ch[k] == 'z') {
cnt++;
}
}
if (cnt == 3) {
if (ans == -1) {
ans = j - i;
} else {
ans = min(ans, j - i);
}
}
}
}
if (ans == -1) {
cout << 'zzz' << endl;
} else {
cout << ans << endl;
}
return 0;
}
算法2
#include <iostream>
#include <string>
using namespace std;
int main() {
string ch;
cin >> ch;
int n = ch.length();
int l = 0, r = 0;
int cnt = 0;
int ans = -1;
while (r < n) {
if (ch[r] == 'z') {
cnt++;
}
while (cnt > 3) {
if (ch[l] == 'z') {
cnt--;
}
l++;
}
if (cnt == 3) {
if (ans == -1) {
ans = r - l + 1;
} else {
ans = min(ans, r - l + 1);
}
}
r++;
}
if (ans == -1) {
cout << 'zzz' << endl;
} else {
cout << ans << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/n33y 著作权归作者所有。请勿转载和采集!