分析题目
1、目标字符数组需要包含原数组所有出现过的字母
2、目标数组任意位置与原数组不同
因此我们考虑直接根据原数组来构建新数组
考虑任意位置与原数组不同,我们将a的位置转到的b的位置(如果b在原数组出现过)
若b从未出现,那么顺位下去c、d、e...直到有一个字母出现过
然后b的位置再转移到下一个字母的位置
以此类推
最后我们得到的数组就满足条件
(举例来说:如果数组含义26个字母,那么原先a的位置会由z代替,b的位置由a代替,c的位置由b代替这样)
那么什么情况是无法构造出答案的呢?
根据我们构造的顺序,如果原数组只出现过一种字母那么将无论如何都无法构建出来
代码
#include "bits/stdc++.h"
using namespace std;
#define int long long
#define endl "\n"
#define PII pair<int,int>
#define PIII pair<int,PII>
const int MOD = 1e9 + 7;
const int N = 3e5;
bool cmp(PII p1, PII p2) {
return p1.first + p1.second < p2.first + p2.second;
}
bool isP(char t1, char t2) {
int c1 = t1 - '0';
int c2 = t2 - '0';
if ((c1 + c2) & 1)return false;
return true;
}
void slu() {
string t;
cin >> t;
string res;
res = t;
vector<vector<int>> a(26);
for (int i = 0; i < t.size(); i++) {
int loc = t[i] - 'a';
a[loc].push_back(i);
}
for (int i = 0; i < 26; i++) {
if (!a[i].empty()) {
for (int j = i + 1; j < 27; j++) {
if (j == 26) {
j = -1;
} else {
if (!a[j].empty()) {
char put = 'a' + i;
for (int k = 0; k < a[j].size(); k++) {
int aim = a[j][k];
res[aim] = put;
}
break;
}
}
}
}
}
for (int i = 0; i < res.size(); i++) {
if (res[i] == t[i]) {
cout << "-1\n";
return;
}
}
cout << res;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
// cin >> T;
T = 1;
while (T--)slu();
}

京公网安备 11010502036488号