CodeForces - 946C:String Transformation(暴力)

39 篇文章 1 订阅
4 篇文章 0 订阅
该博客介绍了一道关于字符串操作的问题,要求通过有限次替换字符操作,将给定字符串转化为包含完整英文字母表的子序列。若无法实现则输出-1。提供了一个C++代码示例来解决这个问题,并指出理解题意是解决问题的关键。
摘要由CSDN通过智能技术生成

题目
You are given a string s consisting of |s| small english letters.

In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.

Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.

输入
The only one line of the input consisting of the string s consisting of |s| (1 ≤ |s| ≤ 105) small english letters.

输出
If you can get a string that can be obtained from the given string and will contain english alphabet as a subsequence, print it. Otherwise print «-1» (without quotes).

样例

样例1输入
aacceeggiikkmmooqqssuuwwyy
输出
abcdefghijklmnopqrstuvwxyz

样例2输入
thereisnoanswer
输出
-1

题意
给出一个字符串,每次操作,你可以将其中的一个字符变成26个英文字母中处于它后面的任意一个字母。
如:a可以变成b~z中任意一个字符,字符z是无法变动的。

问你是否能够通过一系列操作后使得字符串包含a~z?
可以就输出改变之后的字符串,不可以就输出-1。

思路
首先如果字符串的长度小于26就直接输出-1;

长度大于等于26的字符串,我们进行如下操作:
我们设置一个字符ch代表当前处于26个字母中的位置(默认值为a)。
然后我们从头遍历,如果当前的字符<=ch,则把当前字符改为ch,然后让ch向后移。
可以修改成功的条件就是移动了26次,所以再用个变量记录后移次数。

具体看代码,伊丽莎白!

在这里插入图片描述

代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string ss;
    cin>>ss;
    if(ss.size()<26)
        cout<<"-1"<<endl;
    else
    {
        int ans=0,flag=0;
        char ch='a';
        for(int i=0;i<ss.size();i++)
        {
            if(ss[i]<=ch)
            {
                ss[i]=ch;
                ch++;
                ans++;
            }
            if(ans==26)   
            {
                flag=1;
                break;
            }
        }
        if(flag)
            cout<<ss<<endl;
        else
            cout<<"-1"<<endl;
    }
}

虽然是C题但其实只要读懂题意,也不一定是一道难题,你上你也行👍。

下次再见~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值