算法 字符串【英语老师的单词卡消除】

71 篇文章 12 订阅
41 篇文章 1 订阅

一、题目描述

英语老师有无数张单词卡,每张卡片上有一个小写英文单词。现在将卡片打乱,然后依次排成一串:

如:AEEECCFFFCD

每三张连续相同的卡片可以消除,

上述案例最后可以消除成:AD

如果一串可以完全消除成功,则输出0;

如果一串无法完全消除,则输出其消除完所有可消除的单词卡后,剩下的有序串。

 

二、思路

首先要有一个判断函数,

这个函数的功能是判断所给字符串能否进行消除。如果能,则返回消除的那三个字母的前一个字母的下标;如果不能,则返回-1。

还需要一个判断长度函数。

然后在主函数中进行循环判断。

每一次若可消除,则使用字符串切割函数,截取头与尾,切割掉可消除的三个连续字母,

再使用字符串拼接,将原串变成切割后的子串。

重复上述步骤,直到无法再进行消除。

退出循环后,查看剩余字符串的长度:

如果为0,则说明消除成功;

如果不为0,则说明消除不彻底,输出即可。

 

三、代码

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int getLength(string s)
{
	int length = 0;
	string::iterator it = s.begin();
	while (it != s.end())
	{
		it++;
		length++;
	}
	return length;
}

//临时串的判定
bool judgeRest(string ret)
{
	int length = getLength(ret);
	if (length >= 3)
	{
		//仅有倒数三个值相同,才是可消除的。唯一true出口
		if (ret[length - 1] == ret[length - 2] && ret[length - 2] == ret[length - 3])
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

//主串的判定
int judgeString(string s)
{
	string ret;
	int length = getLength(s);
	//当前元素的下标
	int location = 0;
	bool flag = false;
	for (int i = 0; i < length; i++)
	{
		flag = false;
		ret += s[i];
		location++;
		if (judgeRest(ret))
		{
			flag = true;
			break;
		}
	}
	if (flag == true)
	{
		//返回切割起点
		return location - 3;
	}
	else
	{
		return -1;
	}
}

int main()
{
	string a;
	cin >> a;
	while (judgeString(a) != -1)
	{
		int length = getLength(a);
		int location = judgeString(a);
		string front = a.substr(0, location);
		string back = a.substr(location + 3);
		a = front + back;
	}
	if (getLength(a) == 0)
	{
		cout << '0';
	}
	else
	{
		cout << a;
	}
	return 0;
}

运行截图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值