题解 | #字符串加密#

字符串加密

http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3

#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各个字符的频率
map<char, int> count_freq(string& str){
    map<char, int> m;
    for(int i = 0; i < str.size(); i++){
        if(m.find(str[i]) == m.end()){
            m.insert(pair<char, int>(str[i], 1));
        }
        else{
            m[str[i]]++;
        }
    }
    return m;
}

//对key相同的字符只保留第一个
string remove_duplicates(string& str, map<char, int>& m){
    string temp;
    for(int i = 0; i < str.size(); i++){
        if(m[str[i]] > 0){
            temp += str[i];
            m[str[i]] = 0;
        }
    }
    return temp;
}

//key后补A~Z中去除key中字符后的剩余字符
void add_A_to_Z(string& str){
    string temp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for(int i = 0; i < temp.size(); i++){
        if(str.find(temp[i]) == str.npos){
            str += temp[i];
        }
    }
}

//对字符串加密
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转为大写
        freq = count_freq(key);             //统计key各个字符的频率
        key = remove_duplicates(key, freq); //对key相同的字符只保留第一个
        add_A_to_Z(key);                    //key后补A~Z中去除key中字符后的剩余字符
        encryption(str, key);               //对字符加密
        
        cout << str << endl;
    }
    
    return 0;
}
全部评论
干净的写法,而且把加密的字符串以流水的形式使用,非常的优雅
点赞 回复 分享
发布于 2023-07-05 14:37 浙江

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务