描述 | |
---|---|
知识点 | 字符串 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 先输入key和要加密的字符串 |
输出 | 返回加密后的字符串 |
样例输入 | nihao ni |
样例输出 | le |
该题关键是密钥的生成,可以分为三步:
1.原密钥去重
2.将剩下的字母按照字母表的顺序补齐,确保新密钥的大小是26
3.根据新密钥,得到加密后的结果
源代码:
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- vector<char> getNewKey(string key){
- vector<char> newKey;
- int size = key.size();
- bool duplicated[26] = { false };
- for (int i = 0; i < size; i++){
- if (key[i] >= 'A' && key[i] <= 'Z' && duplicated[key[i] - 'A'] == false){
- newKey.push_back(key[i]);
- duplicated[key[i] - 'A'] = true;
- }
- else if (key[i] >= 'a' && key[i] <= 'z' && duplicated[key[i] - 'a'] == false){
- newKey.push_back(key[i]);
- duplicated[key[i] - 'a'] = true;
- }
- }
- return newKey;
- }
- void Encrypt(string key, string data, string& res){
- vector<char> newKey = getNewKey(key);
- char seq[26];//记录密码序列
- bool count[26] = { false };
- for (int i = 0; i < newKey.size(); i++){
- if (newKey[i] <= 'z' && newKey[i] >= 'a'){
- seq[i] = newKey[i] - 'a' + 'A';
- count[newKey[i] - 'a'] = true;
- }
- else{
- seq[i] = newKey[i];
- count[newKey[i] - 'A'] = true;
- }
- }
- int k = newKey.size();
- for (int i = 0; i < 26; i++){
- if (!count[i]){
- seq[k] = 'A' + i;
- k++;
- }
- }
- for (int i = 0; i < data.size(); i++){
- if (data[i] == ' ')
- res[i] = ' ';
- else if(data[i] <= 'z' && data[i] >= 'a'){
- res[i] = seq[data[i] - 'a'] - 'A' + 'a';
- }
- else{
- res[i] = seq[data[i] - 'A'];
- }
- }
- }
- void main(){
- string key, data;
- getline(cin, key);
- //vector<char> newKey = getNewKey(key);
- //for (int i = 0; i < newKey.size(); i++)
- // cout << newKey[i];
- getline(cin,data);
- string res = data;
- Encrypt(key, data, res);
- cout << res << endl;
- }