中南大学上机题——按顺序匹配字符

中南大学上机题——按顺序匹配字符

Problem Description:
大家都关心考试的难易程度,K老师出题有一个规律,在出题之前,它会随机写下一个字符串,只要在这个字符串中能按顺序找到E,A,S,Y四个字母,他出题就会比较简单。你拿到了字符串,请你告诉别人题目难不难吧。
Input:
输入的数据有多组,每组占一行,由一个字符串组成(字符串的长度不超过1000)。
Output:
对于每组输入数据,输出一行,对应一个要求的答案(题目简单就输出easy,难就输出difficult)。
Sample Input:
eAsy
SEoAtSNY
Sample Output:
difficult
easy

算法思路:
把要比较的EASY存储在字符数组中作为辅助数组,设两个指针i,j,指针i指向给定的字符串,j指向辅助数组,当匹配时,i和j同时加一,如果不匹配i加一,如果i指向了给定字符串末尾而j没有指向辅助字符串末尾,则输出difficult,如果j指向了辅助字符串的末尾,则输出easy。

#include<iostream>
#include<string>
using namespace std;
bool function(string str) {
	char tmp[4] = { 'E','A','S','Y' };
	int i = 0, j = 0;
	while (i < str.length() && j < 3) {
		if (str[i] == tmp[j]) {
			i++;
			j++;
		}
		i++;
	}
	if (i >= str.length())
		return false;
	else
		return true;
}
int main() {
	string str;
	int count = 2;
	while (count) {
		cout << "输入字符串:";
		cin >> str;
		if (function(str)) {
			cout << "easy" << endl;
		}
		else
			cout << "difficult" << endl;
		count--;
	}
	return 0;
}

运行测试结果:
在这里插入图片描述

发布了47 篇原创文章 · 获赞 47 · 访问量 1638

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105361557