一. 问题描述
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;
}