java实现斐波那契数列字符串加密
描述
给你一串未加密的字符串sr,通过对字符串的每一个字母进行改变来实现加密,加密方式是在每一个字母sti偏移特定数组元素a0的量,数组a前三位已经赋值:a[0]=1,a[1]=2,a[2]=4。当i>=3时,数组元素a[i]=a[i-1]+a[-2]+a[i-3]。
例如:原文 abcde 加密后 bdgkr,其中偏移量分别是1.2.4,7.13。
输入描述:
第一行为一个整数n(1<=n<=1000),表示有n组测试数据,每组数据包含一行,原文str(只含有小写字母,0<长度<=50)。
输出描述:
每组测试数据输出一行,表示字符串的密文。
用例:
输入:
1
xyz
输出:
yad
java代码实现(开箱即用)
package com.des.data.test;
import java.util.HashMap;
import java.util.Map;
public class StringEncryption {
private static Map<Integer, Integer> memo = new HashMap<>();
public static void main(String[] args) {
String str = "xyz";
System.out.println(solution(str));
}
public static String solution(String str) {
StringBuffer strRes = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int mw = mwei(i + 1);
int ascii = (int) c;
int asciiN = (ascii - 'a' + mw) % 26 + 'a';
char cN = (char) asciiN;
strRes.append(cN);
}
return strRes.toString();
}
private static int mwei(int i) {
if (i <= 2) {
return i;
}
if (i == 3) {
return 4;
}
if (memo.containsKey(i)) {
return memo.get(i);
}
//记忆化搜索来计算斐波那契数列
int resi = mwei(i - 1) + mwei(i - 2);
memo.put(i, resi);
return resi;
}
}