hihocoder-Week243-hiho字符串

hihocoder-Week243-hiho字符串app

 

题目1 : hiho字符串

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

若是一个字符串刚好包含2个'h'、1个'i'和1个'o',咱们就称这个字符串是hiho字符串。  spa

例如"oihateher"、"hugeinputhugeoutput"都是hiho字符串。指针

如今给定一个只包含小写字母的字符串S,小Hi想知道S的全部子串中,最短的hiho字符串是哪一个。code

输入

字符串S  blog

对于80%的数据,S的长度不超过1000  内存

对于100%的数据,S的长度不超过100000字符串

输出

找到S的全部子串中,最短的hiho字符串是哪一个,输出该子串的长度。若是S的子串中没有hiho字符串,输出-1。input

样例输入
happyhahaiohell
样例输出
5

 

题解:string

  双指针滑动窗口,先后两个指针,若是缺乏元素,则前指针前进,若是元素充足,则后指针前进,推动减小窗口。it

 

 

#include <cstdlib> 
#include <cstdio> 
#include <cstring> 
const int MAXN = 100000 + 10;

char ch[MAXN]; 
int len, start_id, end_id, ans;
int h_num, i_num, o_num; 

bool check_validation()
{
	return (h_num >= 2 && i_num >= 1 && o_num >= 1); 
}

bool check_ok()
{
	return (h_num == 2 && i_num == 1 && o_num == 1);
}

void add_item(int idx)
{
	if(ch[idx] == 'h')
	{
		h_num += 1; 
	}else if(ch[idx] == 'i')
	{
		i_num += 1; 
	}else if(ch[idx] == 'o')
	{
		o_num += 1; 
	}
}

void subtract_item(int idx)
{
	if(ch[idx] == 'h')
	{
		h_num -= 1; 
	}else if(ch[idx] == 'i')
	{
		i_num -= 1; 
	}else if(ch[idx] == 'o')
	{
		o_num -= 1;
	}
}

int main(){ 

    scanf("%s", ch); 
    len = strlen(ch); 
    start_id = 0; 
    end_id = 0; 
    h_num = i_num = o_num = 0;
    ans = len + 1; 

    add_item(start_id); 
    ++start_id; 

    while(end_id < start_id)
    {
    	if(check_validation() || start_id >= len)
    	{
    		if(check_ok())
    		{
    			ans = (ans < (start_id - end_id))?(ans):(start_id - end_id); 
    		}
    		subtract_item(end_id);
    		++end_id;  
    	}else{
    		add_item(start_id);
    		++start_id; 
    	}
    }
    if(ans > len)
    {
    	ans = -1; 
    }
    printf("%d\n", ans); 
    return 0; 
} 
相关文章
相关标签/搜索