题解 | 字符串加密

字符串加密

https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3?tpId=37&tqId=21259&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

#include<bits/stdc++.h>
using namespace std;
 
//将key转为大写
void to_upper(string& str){
    for(int i = 0; i < str.size(); i++){
        str[i] = toupper(str[i]);
    }
}
 
//对key相同的字符只保留第一个
string remove_duplicates(const string& str) {
    unordered_map<char, bool> seen;
    string result;
    for (char c : str) {
        if (!seen[c]) {  // 如果字符未见过
            seen[c] = true;
            result += c;
        }
    }
    return result;
}
//key后补A~Z中去除key中字符后的剩余字符
void add_A_to_Z(string& str){
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (char c : alphabet) {
        if (str.find(c) == string::npos) {
            str += c;
        }
    }
}
 
//对字符串加密
void encryption(string& str, string& key){
    for(int i = 0; i < str.size(); i++){
        if(islower(str[i])){          //小写字符
            int index = str[i] - 'a';
            str[i] = tolower(key[index]);
        }
        else if(isupper(str[i])){     //大写字符
            int index = str[i] - 'A';
            str[i] = toupper(key[index]);
        }
    }
}
 
int main(){
    string key;                             //秘钥
    string str;                             //要加密的字符串
     
    while(getline(cin, key) && getline(cin, str)){
        map<char, int> freq;                //存放key中各个字符的频率
        to_upper(key);                      //将key转为大写
        key = remove_duplicates(key); //对key相同的字符只保留第一个
        add_A_to_Z(key);                    //key后补A~Z中去除key中字符后的剩余字符
        encryption(str, key);               //对字符加密
         
        cout << str << endl;
    }
     
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

简历有什么致命问题吗,字节投了60+没有通过一次简历筛
勇敢牛牛不怕困难_l...:我投的字节嵌入式,下午四点投,第二天下午两点收到笔试通知,当时投着玩的,没想到简历真的过了,准备的迟,笔试只做出来最简单的一道,做完笔试,过了一天收到感谢信
点赞 评论 收藏
分享
点赞 评论 收藏
分享
想踩缝纫机的小师弟练...:不理解你们这些人,要放记录就把对方公司名字放出来啊。不然怎么网暴他们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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