题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*;
/**
* 1.对密钥key去重
* 2.去重后,加入字母表的最前面,并将未出现的字母按顺序加入到后面,组成新的26哥字母的字母表
* 3.对照新旧字母表,得到加密后的字符串
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String key = in.nextLine(); // 密钥key TRAILBLAZERS
String str = in.nextLine(); // 要加密的字符串
// 新字母表
List<String> newList = new ArrayList<>();
final String[] split = key.split("");
Set<String> set = new HashSet<>();
// 对密钥key去重,并加入到新字母表的最前面
for (String s : split) {
if (set.add(s)) {
newList.add(s);
}
}
// 原始字母表
List<String> oldList = new ArrayList<>();
char ch = 'a'; // 起始字母a
for (int i = 0; i < 26; i++) {
// 构建旧字母表
oldList.add(ch + "");
// 添加key中未出现的字母到新字母表的后面
if (!newList.contains(ch + "")) {
newList.add(ch + "");
}
ch = (char) (ch + 1); // 每次往后一个字母,如a->b->c->....->z
}
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
for (char cc : chars) {
// 获取字符在旧字母表中的索引位置,再去新字母表相同位置处获取对应字符
sb.append(newList.get(oldList.indexOf(cc +"")));
}
System.out.println(sb);
}
}
}


查看1道真题和解析