题解 | #字符串加密#

字符串加密

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

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

int main() {
    string old_alphabet = "abcdefghijklmnopqrstuvwxyz";
    string new_alphabet, key, plain, cipher;//分别表示新字母表、密钥、明文、密文
    cin >> key >> plain;
    //删除密钥中重复的字符
    unordered_set<char> Set;
    for(int i = 0; i < key.length(); i++){
        for(int j = 0; j < old_alphabet.length(); j++){//从旧字母表中删除密钥中已有的字符
            if(old_alphabet[j] == key[i]){
                old_alphabet.erase(j, 1);
                break;
            }
        }
        if(Set.count(key[i]) != 0){ 
            key.erase(i--, 1);
        }
        Set.insert(key[i]);
    }
    //组合新字母表
    new_alphabet = key + old_alphabet;

    for(int i = 0; i < plain.length(); i++){
        cipher += new_alphabet[plain[i] - 'a'];
    }
    cout << cipher << endl;
    return 0;

}

全部评论
用string.erase()函数时要注意,不写删除的字符数的话默认该位置后面的全删
点赞 回复 分享
发布于 2024-03-09 18:47 河北

相关推荐

点赞 评论 收藏
分享
迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务