hiho字符串(双指针)

题目描述

如果一个字符串恰好包含 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;
}

相似题目

https://ac.nowcoder.com/acm/contest/7509/A

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zaiyang遇见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值