#P3044. 字符串加密(100分)
-
1000ms
Tried: 239
Accepted: 58
Difficulty: 3
所属公司 :
华为od
-
算法标签>模拟
字符串加密(100分)
题目描述
给你一串未加密的字符串 str,通过对字符串的每一个字母进行改变来实现加密。加密方式是将字符串中每个字母 str[i] 偏移特定数组元素 a[i] 的量,数组 a 的前三级已经赋值:a[0] = 1,a[1] = 2,a[2] = 4。
- 当
i >= 3时,数组元素a[i] = (a[i-1] + a[i-2] + a[i-3]) % 26。
解题思路
-
偏移量数组的生成:
- 根据题目,已知数组
a的前三个元素为1, 2, 4。 - 对于
i >= 3的元素,使用递推公式a[i] = (a[i-1] + a[i-2] + a[i-3]) % 26生成。 - 由于字符串长度最大为
50,预先生成长度为51的偏移量数组(索引从0到50)。
- 根据题目,已知数组
-
字符偏移:
- 对于每个字符,根据其在字符串中的位置
i,取对应的偏移量a[i]。 - 计算新字符时需要考虑字母表的循环,即
'z'之后回到'a'。 - 可以使用模运算
(原字符 - 'a' + 偏移量) % 26来计算新的字符。
- 对于每个字符,根据其在字符串中的位置
-
处理多组测试数据:
- 根据输入的
n值,循环处理每组测试数据。 - 对每组数据单独输出加密后的字符串。
- 根据输入的
cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
// 预先生成偏移量数组a,最大长度为51(索引0到50)
const int MAX_LEN = 51;
vector<long long> a(MAX_LEN, 0);
a[0] = 1;
if(MAX_LEN > 1) a[1] = 2;
if(MAX_LEN > 2) a[2] = 4;
for(int i = 3; i < MAX_LEN; i++){
a[i] = (a[i-1] + a[i-2] + a[i-3]) % 26;
}
while(n--){
string s;
cin >> s;
string encrypted = "";
for(int i = 0; i < s.size(); i++){
// 计算偏移后的字符,注意循环
int shift = a[i];
char new_char = 'a' + (s[i] - 'a' + shift) % 26;
encrypted += new_char;
}
cout << encrypted << "\n";
}
return 0;
}
python
def main():
import sys
n_and_rest = sys.stdin.read().split()
n = int(n_and_rest[0])
strings = n_and_rest[1:]
# 预先生成偏移量数组a,最大长度为51(索引0到50)
MAX_LEN = 51
a = [0] * MAX_LEN
a[0] = 1
if MAX_LEN > 1:
a[1] = 2
if MAX_LEN > 2:
a[2] = 4
for i in range(3, MAX_LEN):
a[i] = (a[i-1] + a[i-2] + a[i-3]) % 26
for s in strings:
encrypted = []
for i, ch in enumerate(s):
shift = a[i]
# 计算新的字符,考虑循环
new_char = chr(ord('a') + (ord(ch) - ord('a') + shift) % 26)
encrypted.append(new_char)
print(''.join(encrypted))
if __name__ == "__main__":
main()
java
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
// 预先生成偏移量数组a,最大长度为51(索引0到50)
long[] a = new long[51];
a[0] = 1;
if(a.length >1) a[1] = 2;
if(a.length >2) a[2] = 4;
for(int i=3;i<51;i++){
a[i] = (a[i-1] + a[i-2] + a[i-3]) % 26;
}
for(int test=0; test<n; test++){
String s = br.readLine();
StringBuilder encrypted = new StringBuilder();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
long shift = a[i];
// 计算新的字符,考虑循环
char newChar = (char)('a' + ((ch - 'a') + shift) % 26 );
encrypted.append(newChar);
}
System.out.println(encrypted.toString());
}
}
}
题目描述
给你一串未加密的字符串 str ,通过对字符串的每一个字母进行改变来实现加密,加密方式是在每一个字母 str[i] 偏移特定数组元素 a[i] 的量,数组 a 前三位已经赋值:a[0]=1,a[1]=2,a[2]=4。
当 i>=3 时,数组元素 a[i]=a[i−1]+a[i−2]+a[i−3] 。
例如:原文 abcde 加密后 bdgkr ,其中偏移量分别是 1,2,4,7,13。
输入描述
第一行为一个整数 n(1<=n<=1000),表示有 n 组测试数据,每组数据包含一行,原文 str(只含有小写字母,0< 长度 <=50)。
输出描述
每组测试数据输出一行,表示字符串的密文。
样例1
输入
1
xy
输出
ya
说明
第一个字符 x 偏移量是 1 ,即为 y ,第二个字符 y 偏移量是 2 ,即为 a 。