C++ string elimination eoj1026

The topics are as follows:

 The basic idea is to insert the same character in front of each character by traversing, and find the number of characters eliminated.

For example, for the string ABC, calculate the total number of characters eliminated by AABC, ABBC, and ABCC, and output the maximum value.

#include <iostream>
#include<string>
#include<map>

using namespace std;
/*

计算删除总数:遍历字符串
从下标为1开始遍历,每次看一下和前面的字符是否相同若相同则进入循环依次往后遍历
直到出现不同的字符为止
将erasenum+上相同的字符串,iserase设为true
用一个map记录相同字符出现的首次位置和长度
遍历完之后
把这些相同的字符删掉,并在map中删掉对应的pair
当iserase为false时进入下一次

*/

int biggestclear(string s)
{
    int biggestnum = 0;
    for (int j = 0; j < s.length(); j++)
    {
        string copy = s;
        copy.insert(j,1, s[j]);
        //计算删除总数
        int erasenum = 0;
        while (1)
        {
            bool iserase = false;
            map<int, int> storeerase;
            int m = 1;
            while( m < copy.length())
            {
                if (copy[m] == copy[m - 1])
                {
                    iserase = true;
                    int samelen = 2;
                    int exp = m + 1;
                    while (copy[exp] == copy[m] && exp < copy.length())
                    {
                        exp++;
                        samelen++;
                    }
                    storeerase[m - 1] = samelen;
                    erasenum += samelen;
                    m += samelen - 1;
                }
                else
                    m++;
            }

            while(!storeerase.empty())
            {
                map<int, int>::iterator iter = storeerase.end();
                iter--;
                copy.erase(iter->first, iter->second);
                storeerase.erase(iter);
            }
            if (!iserase) break;
        }
        if (erasenum > biggestnum) biggestnum = erasenum;

    }
    return biggestnum;
}

int main()
{
    int quesnum; cin >> quesnum;
    for (int i = 0; i < quesnum; i++)
    {
        cout << "case #" << i << ":" << endl;
        string s;
        cin >> s;
        cout << biggestclear(s) << endl;

    }

    return 0;
}

There are a lot of details that need to be paid attention to. Look at the code for details~ Especially the operation of deleting substrings when eliminating:

It can’t be deleted while traversing, which will lead to loop errors, so I used a map to store the starting position and length to be deleted, key (starting position) = value (length), and delete it uniformly after looping once, and from Delete from the back to the front, and delete from the front to the back will make an error (the coordinates will change after deleting once)

that's all finally succeeded AC

 

 

Guess you like

Origin blog.csdn.net/weixin_61720360/article/details/123668720