#1039 : 字符消除

字符消除,正好简单复习一下,c++中的容器。容器使用起来还是比较方便的,包括string类型,代码还是要经常写写,才知道自己那些地方有问题。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string stringRemove(string s){
    string temp;
    char temp_c;
    for (int i = 0; i < s.size(); i++)
    {
        temp_c = s[i];
        temp.push_back(temp_c);
        if (s[i + 1] == temp_c)
        {
            temp.pop_back();
        }
        while (s[i + 1] == temp_c){
            i++;
        }
    }
    if (temp.size() == s.size())
    {
        return temp;
    }
    else{
        temp = stringRemove(temp);
    }
    return temp;//递归忘了这一句
}

int main()
{
    string s;
    string sout;//字符消除后的字符串
    int n;//输入数据的个数
    int count = 0;//消除次数计数
    cin >> n;
    int len;//记录消除结果的长度
    int min;//记录消除结果中最短的
    int position;//记录消除结果中最短的
    char whichOne;//记录消除的位置
    int score;//记录消除得分
    int i, j;
    while (n--)
    {
        cin >> s;
        min = s.size();
        //cout << "输出" << endl;
        string::iterator begin = s.begin();
        string::iterator insert;
        string s_copy;
        for (i = 0; i <= s.size(); i++)
        {
            for (j = 65; j < 68; j++)
            {
                insert = s.insert(begin, j);
                //cout << s << endl;
                s_copy = s;
                sout = stringRemove(s_copy);
                //cout << "字符串所剩长度:" << sout.size() << endl;
                len = sout.size();
                if (len <= min)
                {
                    min = len;
                    position = i;
                    whichOne = j;
                    score = s.size() - sout.size();
                }
                s.erase(insert);
            }
            if (i != s.size())
            {
                begin++;
            }
        }
        cout << score << endl;
        /*cout <<"位置:"<<position <<" "<< whichOne<<" 得分:"<<score << endl;*/
    }
    return 0;
}

第一组数据:在”ABCBCCCAA”的第2个字符后插入’C’得到”ABCCBCCCAA”,消除后得到”A”,总共消除9个字符(包括插入的’C’)。

第二组数据:”AAA”插入’A’得到”AAAA”,消除后得到”“,总共消除4个字符。

第三组数据:无论是插入字符后得到”AABC”,”ABBC”还是”ABCC”都最多消除2个字符。
样例输入
3
ABCBCCCAA
AAA
ABC

样例输出
9
4
2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值