题目来自牛客网周赛
牛牛截获了一段由凯撒密码加密过的密文,凯撒密码指的是将字符偏移一定的单位,例如若偏移量为2,则a替换为c,b替换为d,c替换为e,…,z替换为b。若加密nowcoder,则密文为pqyeqfgt。现在牛牛发现对方加密包括数字、大写字母、小写字母,即0-9、A-Z、a-z的排列顺序进行偏移,现在牛牛截获了对方的一段密文以及偏移量,你能帮助牛牛破解密文吗。即给定一段密文str和偏移量d,求对应的明文。
输入 “pqyeqfgt”,2
输出 “nowcoder”
示例2
输入"123ABCabc",3
输出"yz0789XYZ"
import java.util.ArrayList;
public class Solution {
/**
* 解密密文
*
* @param str string字符串 密文
* @param d int整型 偏移量
* @return string字符串
*/
public String decode(String str, int d) {
StringBuilder res = new StringBuilder();
ArrayList al = new ArrayList();
char[] arr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'};
for (char n : arr)
al.add(n);
for (int i = 0; i < str.length(); i++) {
int index = al.indexOf(str.charAt(i));
if (index - d < 0) {
index += 62;
}
res.append(al.get(index - d));
}
return res.toString();
}
}