Codeforces 946C String Transformation 贪心

题目链接:String Transformation

题意

给定一个字符串 s ,可以将这个字符串的任意一个字符变成它的下一个字符(按 A S C I I 顺序),问给定的字符串能否通过任意次这种操作成为一个含有子字符序列 a b c z 的字符串。

输入

输出为一个只包含小写字符的字符串 s   ( 1 | s | 10 5 )

输出

如果无法成为满足题意的字符串,输出 1 ,否则输出转化后的字符串,如果有多解输出任意一个。

样例

输入
aacceeggiikkmmooqqssuuwwyy
输出
abcdefghijklmnopqrstuvwxyz
输入
thereisnoanswer
输出
-1

题解

用一个 c h 来记录当前位置的字符需要变成的子序列 a b c z 中的字符,如果当前字符的 A S C I I 不大于 c h ,说明当前字符可以变成 c h ,然后将 c h + + 成为下一个字符,最后判断 c h 是否到达 z + 1

过题代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;

#define LL long long
const int maxn = 100000 + 100;
char str[maxn];

int main() {
    #ifdef LOCAL
        freopen("test.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    #endif // LOCAL
    ios::sync_with_stdio(false);

    while(scanf("%s", str) != EOF) {
        char ch = 'a';
        for(int i = 0; str[i]; ++i) {
            if(str[i] <= ch) {
                if(ch <= 'z') {
                    str[i] = ch;
                    ++ch;
                }
            }
        }
        if(ch == 'z' + 1) {
            printf("%s\n", str);
        } else {
            printf("-1\n");
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/CSDNjiangshan/article/details/81365610