codeforce C. Remove Adjacent

题意:
给你一个字符串,每当一个字符的相邻字符在字母表中是它前面的字符,你就可以选择删掉它。问最大可以删去的字符是多少
思路:
最开始想的是从头开始判断,但是情况太多,总是会漏掉。注意到这道题数据很小,所以不如直接暴力求解。每次我们都循环一边,找到满足删去条件的最大的字符,我们把它删掉,然后继续循环,直到没有符合条件的。
代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
string s;
int n, id;
bool slove()
{
    char maxx = 'a';
    bool flag = 0;
    for(int i = 1; i <= n; ++i)
    {
        if(s[i] != 'a' && (s[i - 1] == s[i] - 1 || s[i + 1] == s[i] - 1))
        {
            if(maxx < s[i])
            {
                flag = 1;
                maxx = s[i];
                id = i;
            }
        }
    }
    return flag;
}
 
int main()
{
    scanf("%d",&n);
    getchar();
    getline(cin, s);
    s = '#' + s + '#';
    string :: iterator k;
    int cnt = 0;
    while(slove())
    {
        k = s.begin() + id;
        s.erase(k);
        n--;
        cnt++;
    }
    cout<<cnt<<'\n';
    return 0;
}
发布了107 篇原创文章 · 获赞 3 · 访问量 7100

猜你喜欢

转载自blog.csdn.net/qq_43504141/article/details/104618903