训练赛002 H题 -Perfect String

原题

A string is called beautiful if no two consecutive characters are equal. For example, “ababcb”, “a” and “abab” are beautiful strings, while “aaaaaa”, “abaa” and “bb” are not.

Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters ‘a’, ‘b’, ‘c’ and ‘?’. Ahcl needs to replace each character ‘?’ with one of the three characters ‘a’, ‘b’ or ‘c’, such that the resulting string is beautiful. Please help him!

More formally, after replacing all characters ‘?’, the condition si≠si+1 should be satisfied for all 1≤i≤|s|−1, where |s| is the length of the string s.

Input
The first line contains positive integer t (1≤t≤1000) — the number of test cases. Next t lines contain the descriptions of test cases.

Each line contains a non-empty string s consisting of only characters ‘a’, ‘b’, ‘c’ and ‘?’.

It is guaranteed that in each test case a string s has at least one character ‘?’. The sum of lengths of strings s in all test cases does not exceed 105.

Output
For each test case given in the input print the answer in the following format:

If it is impossible to create a beautiful string, print “-1” (without quotes);
Otherwise, print the resulting beautiful string after replacing all ‘?’ characters. If there are multiple answers, you can print any of them.
Example
Input
3
a???cb
a??bbc
a?b?c
Output
ababcb
-1
acbac
Note
In the first test case, all possible correct answers are “ababcb”, “abcacb”, “abcbcb”, “acabcb” and “acbacb”. The two answers “abcbab” and “abaabc” are incorrect, because you can replace only ‘?’ characters and the resulting string must be beautiful.

In the second test case, it is impossible to create a beautiful string, because the 4-th and 5-th characters will be always equal.

In the third test case, the only answer is “acbac”.

题解

本题中?转换为其他字母的时候一定不会和旁边的字母重复(因为?旁边最多有两个不同字母,但是它可以换为三种字母),因此只需判断除?其他是否有连续重复即可,?变为什么字母可以自定。

错因

这个题我想出了怎么解题,但是不知道应该怎么用很少的判断把?变为任意一个字母,我觉得太麻烦就没继续做,后来看了题解发现其实只要两边不等于一个字母就可以取用,换成什么直接判断就可以。

代码

#include < i o s t r e a m > <iostream> <iostream>
#include < s t r i n g > <string> <string>
using namespace std;
int main()
{
int t,l,i,p;
string a;
char b;
cin>>t;
while(t–)
{
cin>>a;
l=a.size();
for(i=0;i<l;i++)
{
p=1;
if(a[i]!=’?’)
{
if(a[i] = = == ==a[i+1])
{
p=-1;
break;
}
}
else{
if(i==0)
{
if(a[1]!=‘a’)a[i]=‘a’;else
if(a[1]!=‘b’)a[i]=‘b’;else
if(a[1]!=‘c’)a[i]=‘c’;
}
else{
if(a[i-1]!=‘a’&&a[i+1]!=‘a’)a[i]=‘a’;else
if(a[i-1]!=‘b’&&a[i+1]!=‘b’)a[i]=‘b’;else
if(a[i-1]!=‘c’&&a[i+1]!=‘c’)a[i]=‘c’;
}
}
}
if(p = = == ==-1)
cout<<p<<endl;
else
cout<<a<<endl;
}
return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值