题目描述
给出原文字符串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,表示n组测试数据。每组数据包含一行,原文str(只含有小写字母,长度大于0小于50)。
输出描述
每组测试数据输出一行,表示密文。
示例1
输入
1
xy
输出
ya
说明:第一个字符x偏移量是1,即为y,第二个字符y偏移量是2,即为a。
题解
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入测试数据组数:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character after reading n
for (int i = 0; i < n; i++) {
System.out.println("请输入第"+(i+1)+"组测试数据:");
String str = scanner.nextLine();
String encryptedStr = encryptString(str);
System.out.println(encryptedStr);
}
}
public static String encryptString(String str) {
int[] a = new int[50];
a[0] = 1;
a[1] = 2;
a[2] = 4;
for (int i = 3; i < 50; i++) {
a[i] = a[i - 1] + a[i - 2] + a[i - 3];
}
char[] charArray = str.toCharArray();
StringBuilder encryptedStr = new StringBuilder();
for (int i = 0; i < charArray.length; i++) {
int offset = a[i];
char encryptedChar = (char) (((charArray[i] - 'a' + offset) % 26) + 'a');
encryptedStr.append(encryptedChar);
}
return encryptedStr.toString();
}