Codeforces #58A Chat Room

一. 问题描述

 Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word s.  

二.分析及代码

  题目本身非常简单,但在具体编译是却发现自己运行与评测机运行结果不同,后发现是因为初始化问题导致的数组越界,今后做题时要注意变量的初始化问题以及数组是否越界

原代码

#include<stdio.h>
#include<string.h>
main(){
	char st[110],st1[5]={'h','e','l','l','o'};
	int i,j,n,k;
	scanf("%s",&st);
	k=0;
	for (i=0;i<strlen(st);i++){
		if (st[i]==st1[k]){//此处当k>4后st1后的字符便没有初始化,数组越界,于是造成错误
			k++;
		}
	}
	if (k==5){
		printf("YES",k);
	}
	else {
		printf("NO",k);
	}
	return 0;
}

改进后代码

#include<stdio.h>
#include<string.h>
main(){
	char st[110],st1[5]={'h','e','l','l','o'};//在st中依次与st1中比较得到结果即可
	int i,k;
	scanf("%s",&st);
	k=0;
	for (i=0;i<strlen(st);i++){
		if (st[i]==st1[k]){
			k++;
			if (k==5) {//确保数组不会越界
				break;
			}
		}
	}
	if (k==5){
		printf("YES\n");
	}
	else {
		printf("NO\n");
	}
	return 0;
}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值