练习题 Chat room

Topic

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.

Input

The first and only line contains the word s, which Vasya typed. This
word consisits of small Latin letters, its length is no less that 1
and no more than 100 letters.

Output

If Vasya managed to say hello, print “YES”, otherwise print “NO”.

Examples
Input

ahhellllloou

Output

YES

Input

hlelo

Output

NO

刚看到这道题,就想着每输入“hello”中的一个字符就做一个标记,比如输入‘h”后就做一个标记,只有存在这个标记后输入的‘e’才是有效的,以此类推,后边的字符也是这样操作,到最后进行一次判断,看是否完整输入了“hello”。
结果调试代码调试了半天,样例死活就是不通过…
现附上我的憨憨代码

								**错误代码**
#include<iostream>
#include<string>
using namespace std;
int main()
{
	char ch;
	int flag = 0;
	while (cin >> ch)
	{
		if (ch == 'h' && flag == 0)
			flag++; 
		if (ch == 'e' && flag == 1)
			flag ++;
		if (ch == 'l' && flag == 2)
			flag ++;
		if (ch == 'l' && flag == 3)//输入一次‘l’会被运算两次,导致代码错误
			flag ++;
		if (ch == 'o' && flag == 4)
		{ 
			flag ++; 
			break;
		}
	}
	if (flag == 5)
		cout << "YES" << endl;
	if(flag!=5)
		cout << "NO" << endl;
	return 0;
}

经大佬指正,现已清楚代码的问题所在

对于这个题目,可以用另外一种方法来做,字符串匹配!!!!

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	int n,k=0;
	char str[5] = { 'h','e','l','l','o' };
	char a[105];
	cin >> a;
	n = strlen(a);
	for (int i = 0; i < n; i++)
	{
		if (a[i] == str[k])k++;
		if (k == 5)break;
	}
	if (k == 5)cout << "YES" << endl;
	else cout << "NO" << endl;
	return 0;
}

做题要注意转化思维啊,真的很重要。一种方法走不通了,就从另外一个角度思考思考问题,可萌就会有意外收获//

发布了14 篇原创文章 · 获赞 18 · 访问量 1666

猜你喜欢

转载自blog.csdn.net/SDAU_LGX/article/details/104760764