hihocoder-Week243-hiho字符串
题目1 : hiho字符串
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
如果一个字符串恰好包含2个'h'、1个'i'和1个'o',我们就称这个字符串是hiho字符串。
例如"oihateher"、"hugeinputhugeoutput"都是hiho字符串。
现在给定一个只包含小写字母的字符串S,小Hi想知道S的所有子串中,最短的hiho字符串是哪个。
输入
字符串S
对于80%的数据,S的长度不超过1000
对于100%的数据,S的长度不超过100000
输出
找到S的所有子串中,最短的hiho字符串是哪个,输出该子串的长度。如果S的子串中没有hiho字符串,输出-1。
-
样例输入
-
happyhahaiohell
样例输出
-
5
题解:
双指针滑动窗口,前后两个指针,如果缺少元素,则前指针前进,如果元素充足,则后指针前进,推进减少窗口。
#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;
}