题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
#include <iostream>
#include <string>
using namespace std;
//核心代码,加密和解密通用
string transform(string str, const string &plain, const string &cipher)
{
for (char &x : str)
{
int index = -1;
index = plain.find(x);//查到字符在明文字典中的索引
x = cipher.at(index);//将字符修改成密文字典中对应索引的字符
}
return str;//返回变换后的字符串
}
int main() {
//定义两个字符串,一个明文字典,一个密文字典
const string plain = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const string cipher = "bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA1234567890";
//读入输入
string str1, str2;
cin >> str1;
cin >> str2;
//理解加密和解密互逆,只要将字典颠倒传给函数即可
cout << transform(str1, plain, cipher) << endl;
cout << transform(str2, cipher, plain) << endl;
return 0;
}
// 64 位输出请用 printf("%lld")
使用字典法,可以比较简洁