题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String key = "";
String text = "";
while (in.hasNext()) { // 注意 while 处理多个 case
key = in.nextLine();
text = in.nextLine();
}
//构建原字母表
char[] originAlphabet = new char[52];
char bigHead = 'A';
char smallHead = 'a';
for (int i = 0; i < 26; i++) {
originAlphabet[i] = bigHead;
bigHead++;
}
for (int i = 26; i < 52; i++) {
originAlphabet[i] = smallHead;
smallHead++;
}
//添加密钥并大写去重后置顶
char[] pwdAlphabet = new char[52];
char[] keyArr = key.toCharArray();
//去重大写进组
int index = 0;
for (char c : keyArr) {
if (c >= 'a' && c <= 'z') {
char small2Big = (char)(c + 'A' - 'a');
if (!aInB(small2Big, pwdAlphabet)) {
pwdAlphabet[index] = small2Big;
index++;
}
} else {
if (!aInB(c, pwdAlphabet)) {
pwdAlphabet[index] = c;
index++;
}
}
}
//System.out.println(i);
//剩余字母进组
int originIndex = 0;
while (index < 26 && originIndex < 26) {
if (!aInB(originAlphabet[originIndex], pwdAlphabet)) {
pwdAlphabet[index] = originAlphabet[originIndex];
index++;
}
originIndex++;
}
//完善小写字母
while (index < 52) {
pwdAlphabet[index] = (char)(pwdAlphabet[index - 26] - 'A' + 'a');
index++;
}
//System.out.println(originAlphabet);
//System.out.println(pwdAlphabet);
//加密输入串
char[] textArr = text.toCharArray();
char[] encodedArr = new char[textArr.length];
int textIndex = 0;
for (char c : textArr) {
if (c >= 'A' && c <= 'Z') {
encodedArr[textIndex] = pwdAlphabet[c - 'A'];
} else {
encodedArr[textIndex] = pwdAlphabet[c - 'a' + 26];
}
textIndex++;
}
System.out.println(encodedArr);
}
private static boolean aInB(char c, char[] arr) {
for (int i = 0; i < arr.length; i++) {
if (c == arr[i]) {
return true;
}
}
return false;
}
}
没有看到测试用例都是用小写字母,建立了大小写字母的密码表,里面两个数组的创建比最后的加密更困难:经历了两个for创建正序大小写字母表,密钥改大写,密钥去重进组,剩余大写进组,通过大写改小写进组,使用的都是很繁琐的字符运算和判断逻辑。两个数组创建好了就简单了,最后我没有通过查找对应关系来加密,而是直接对当前字符运算出加密字符应该在哪个位置并获取,所以其实第一个正序字母表数组也可以不创建的。
后面看了题解有大神说可以用LinkedHashSet构建原序去重集合,我当时想用的是HashSet但发现输出的不是原序就放弃了,想找LinkedHashSet这种但不知道有所以用了最繁琐的方式,反正兄弟们尝试去用这个结构可以简单很多。
这篇纯粹记录下自己写的这个像shit一样的代码。

