#include<bits/stdc++.h>
using namespace std;
static string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//双表代替加密
//第一种加密
int first_change(char& letter)
{
int location;
string key1 = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
//string alphabet = "abcdefghijklmnopqrstuvwxyz";
if (letter != ' ')
{
location = alphabet.find_first_of(letter);
letter = key1[location];
}
return 1;
}
//第二种加密
int second_change(char& letter)
{
int location;
string key2 = "lkjhgfdsaqwertyuiopmnbzxcvLKJHGFDSAQWERTYUIOPMNBZXCV";
//string alphabet = "abcdefghijklmnopqrstuvwxyz";
if (letter != ' ')
{
location = alphabet.find_first_of(letter);
letter = key2[location];
}
return 1;
}
//加密时:判断该字母第几次出现在句子当中
int judeg_encryption(const char letter)
{
static map<char, int> letter_nums
{
{'a',0},{'b',0},{'c',0},{'d',0},{'e',0},{'f',0},
{'g',0},{'h',0},{'i',0},{'g',0},{'k',0},{'l',0},
{'m',0},{'n',0},{'o',0},{'p',0},{'q',0},{'r',0},
{'s',0},{'t',0},{'u',0},{'v',0},{'w',0},{'x',0},
{'y',0},{'z',0},
{'A',0},{'B',0},{'C',0},{'D',0},{'E',0},{'F',0},
{'G',0},{'H',0},{'I',0},{'G',0},{'K',0},{'L',0},
{'M',0},{'N',0},{'O',0},{'P',0},{'Q',0},{'R',0},
{'S',0},{'T',0},{'U',0},{'V',0},{'W',0},{'X',0},
{'Y',0},{'Z',0}
};
if (letter != ' ')
{
letter_nums[letter]++;
}
return letter_nums[letter] % 2;
//若返回值为1,对应第一次加密方法
//若返回值为0,对应第二次加密方法
}
//加密
string encryption(string& sentence, vector<int>& record)
{
char letter;
int option; //接受选择判断函数的返回值
for (int i = 0; i < sentence.length(); i++)
{
if (sentence[i] != ' ')
{
letter = sentence[i];
option = judeg_encryption(letter);
if (option == 1)
{
first_change(letter);
sentence[i] = letter;
record.push_back(1);
}
if (option == 0)
{
second_change(letter);
sentence[i] = letter;
record.push_back(0);
}
}
}
return sentence;
}
//第一种解密
int first_decode(char& letter)
{
int location;
string key1 = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
//string alphabet = "abcdefghijklmnopqrstuvwxyz";
if (letter != ' ')
{
location = key1.find_first_of(letter);
letter = alphabet[location];
}
return 1;
}
//第二种解密
int second_decode(char& letter)
{
int location;
string key2 = "lkjhgfdsaqwertyuiopmnbzxcvLKJHGFDSAQWERTYUIOPMNBZXCV";
//string alphabet = "abcdefghijklmnopqrstuvwxyz";
if (letter != ' ')
{
location = key2.find_first_of(letter);
letter = alphabet[location];
}
return 1;
}
string decode(string& sentence, const vector<int> record)
{
char letter;
int j = 0;
for (int i = 0; i < sentence.length(); i++)
{
if (sentence[i] != ' ')
{
if (record[j] == 1)
{
letter = sentence[i];
first_decode(letter);
sentence[i] = letter;
}
if (record[j] == 0)
{
letter = sentence[i];
second_decode(letter);
sentence[i] = letter;
}
j++;
}
}
return sentence;
}
int main()
{
static vector<int> record;
string sentence;
cout << "please input what you want to encrypt:" << endl;
getline(cin, sentence);
cout << "加密后" << endl;
cout << encryption(sentence, record) << endl;
cout << "解密后" << endl;
cout << decode(sentence, record);
}