一、题目描述
英语老师有无数张单词卡,每张卡片上有一个小写英文单词。现在将卡片打乱,然后依次排成一串:
如: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;
}
运行截图: