题目描述
如果一个字符串恰好包含 2 2 2个 h h h、 1 1 1个 i i i和 1 1 1个 o o o,我们就称这个字符串是 h i h o hiho hiho字符串。
例如 " o i h a t e h e r " 、 " h u g e i n p u t h u g e o u t p u t " "oihateher"、"hugeinputhugeoutput" "oihateher"、"hugeinputhugeoutput"都是 h i h o hiho hiho字符串。
现在给定一个只包含小写字母的字符串 S S S,小Hi想知道 S S S的所有子串中,最短的 h i h o hiho hiho字符串是哪个。
Input
一个字符串S
Output
找到
S
S
S的所有子串中,最短的
h
i
h
o
hiho
hiho字符串是哪个,输出该子串的长度。如果
S
S
S的子串中没有
h
i
h
o
hiho
hiho字符串,输出
−
1
-1
−1。
样例1
Sample Input
happyhahaiohell
Sample Output
5
提示/说明
对于 80 % 80\% 80%的数据, S S S的长度不超过 1000 1000 1000
对于 100 % 100\% 100%的数据, S S S的长度不超过 100000 100000 100000
提交链接
https://www.luogu.com.cn/problem/T291600
解析
1.定义一个数组表明目标串的特点:
int a[]= {'h'-'a','i'-'a','o'-'a'};
2.开一个数组记录每个字母出现的次数
int num[N];
for(int i=0; i<len; i++)
num[ch[i]-'a']++;
3.定义一个变量记录左阶
int l=0;
参考代码:
#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
const int INF=0x3f3f3f3f;
int a[]= {'h'-'a','i'-'a','o'-'a'};
char ch[N];
int num[N];
int main()
{
memset(num,0,sizeof(num));
scanf("%s",ch);
int len=strlen(ch);
int l=0;
int mi=N;
for(int i=0; i<len; i++)
{
bool book=false;
num[ch[i]-'a']++;
while(num[a[0]]>=2&&num[a[1]]>=1&&num[a[2]]>=1)
{
book=true;
num[ch[l]-'a']--;///再满足情况的前提下,减去左边没用的区间
l++;
}
if(book)///执行了while循环,说明这一段存在目标字符串
{
l--;
num[ch[l]-'a']++;
}
if(num[a[0]]==2&&num[a[1]]==1&&num[a[2]]==1)///更新最小值
mi=min(mi,i-l+1);
}
if(mi==N)
printf("-1\n");
else
printf("%d\n",mi);
return 0;
}