题解 | 小红的字符串构造

小红的字符串构造

https://www.nowcoder.com/practice/3e4b4dabc2e444e384c3ae62ac7dd84e

#include <iostream>
#include <unordered_set>
#include <vector>
#include <algorithm>
using namespace std;


string constructT(string s) {
    unordered_set<char> charSet(s.begin(), s.end());  // 提取无序字符集
    vector<char> uniqueChars(charSet.begin(),charSet.end());  // 转为数组便于操作
    if(charSet.size()<=1){
        return "-1";
    }
    string t = s;  // 初始化 t 与 s 长度相同

    // 调整顺序,右移一位,确保字符与对应位置不同
    int n = uniqueChars.size();
    for (int i = 0; i < s.size(); ++i) {
        auto mid=find(uniqueChars.begin(),uniqueChars.end(),s[i]);
        if(mid!=uniqueChars.end()){
            int mit =(mid-uniqueChars.begin()+1)%n;
            t[i]=uniqueChars[mit];
        }
    }
    return t;
}

int main() {
    string s;
    cin >> s;

    string t = constructT(s);
    cout << t << endl;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
嵐jlu:我是山川🐔里🐔🧱的,阿里系简历全过; 你这简历一看就还是半成品啊,没有荣誉经历奖项什么的吗?
投递阿里巴巴集团等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务