C++ 字符串加密解密算法测试 - 判断是否可解密
C++ 字符串加密解密算法测试 - 判断是否可解密
小码哥是一名黑客,他最近刚彩票中奖,由于还没兑换,小码哥十分担心彩票被盗 (小码哥过分谨慎了),他想为自己的保险箱设新的密码,顺便他想让你测试编码。
现有两种编码方式:
- 对于已知字符串中的任意字符,用其他字符交换,如用'A'和'B'交换,原先用'A'的地方换成'B',用'B'的地方换成'A'。
- 对于当前字符串,打乱字符顺序。
先给你一个加密后的字符串和加密前的字符串,判断加密前的字符串是否能得到加密后的字符串。字符串中字符均为大写字母。
格式
输入格式: 第一行加密后的字符串 第二行加密前的字符串 有多组数据输入 .
输出格式: 输出'YES'或'NO'
样例1
输入:
JWPUDJSTVP
VICTORIOUS
MAMA
ROME
HAHA
HEHE
AAA
AAA
NEERCISTHEBEST
SECRETMESSAGES
输出:
YES
NO
YES
YES
NO
备注:
所有字符串长度不超过100
代码内容:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// 加密函数1,用其他字符交换
string encrypt1(string s, string key) {
int n = s.size();
for (int i = 0; i < n; i++) {
char c = s[i];
int pos = key.find(c);
if (pos != string::npos) { // 如果c在key中出现过
s[i] = key[(pos+1)%26]; // 用key中c的下一个字符替换c
}
}
return s;
}
// 加密函数2,打乱字符顺序
string encrypt2(string s) {
random_shuffle(s.begin(), s.end());
return s;
}
// 解密函数1,用其他字符交换
string decrypt1(string s, string key) {
int n = s.size();
for (int i = 0; i < n; i++) {
char c = s[i];
int pos = key.find(c);
if (pos != string::npos) { // 如果c在key中出现过
s[i] = key[(pos+25)%26]; // 用key中c的上一个字符替换c
}
}
return s;
}
// 解密函数2,恢复字符顺序
string decrypt2(string s, string ori) {
sort(ori.begin(), ori.end()); // 把加密前的字符串排序
int n = s.size();
for (int i = 0; i < n; i++) {
char c = s[i];
int pos = ori.find(c);
if (pos != string::npos) { // 如果c在ori中出现过
s[i] = ori[pos]; // 用ori中c的位置替换c
}
}
return s;
}
int main() {
string s, ori;
while (cin >> s >> ori) {
if (s.size() != ori.size()) { // 如果长度不同,一定无法得到
cout << "NO" << endl;
continue;
}
string key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 枚举用哪两个字符交换
for (int i = 0; i < 26; i++) {
for (int j = i+1; j < 26; j++) {
string new_key = key;
swap(new_key[i], new_key[j]); // 用new_key替换key
string tmp = decrypt1(s, new_key);
tmp = decrypt2(tmp, ori);
tmp = encrypt2(tmp);
tmp = encrypt1(tmp, new_key);
if (tmp == s) { // 如果能得到加密后的字符串,则输出YES
cout << "YES" << endl;
goto end;
}
}
}
cout << "NO" << endl; // 无法得到加密后的字符串
end:;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nJwI 著作权归作者所有。请勿转载和采集!