题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
// 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
// N I H A O B C D E F G J K L M P Q R S T U V W X Y Z
Scanner scanner = new Scanner(System.in);
String key = scanner.nextLine();
String pwd = scanner.nextLine();
// 将key去重
List<Character> strList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int length = key.length();
for (int i = 0; i < length; i++) {
if (!strList.contains(key.charAt(i))) {
strList.add(key.charAt(i));
sb.append(key.charAt(i));
}
}
key = sb.toString();
List<Character> totalList = new ArrayList<>();
for (int i = 97; i <= 122; i++) {
totalList.add((char) i);
}
// 将key转成List
List<Character> list = new ArrayList<>();
length = key.length();
for (int i = 0; i < length; i++) {
list.add(key.charAt(i));
}
totalList.removeAll(list);
Map<Character, Character> map = new HashMap<>();
// 得到加密的新字母表
int k = 0;
for (int i = 97, j = 0; i <= 122; i++) {
// 转成字符
char keyName = (char) i;
if (j < length) {
map.put(keyName, key.charAt(j++));
} else {
// 说明已经填充完了钥匙
// 将A-Z中没有出现过的拿到
map.put(keyName, totalList.get(k++));
}
}
int n = pwd.length();
for (int i = 0; i < n; i++) {
System.out.print(map.get(pwd.charAt(i)));
}
}
}
关注点:1.密钥中的字符可能重复,去重; 2.建立映射关系
思路:1.密钥去重 2.建立a-z的26位集合 3.集合去重(26位集合removeAll密钥的集合) 4.建立映射关系(先将密钥按照顺序建立映射,再讲剩余的集合按照顺序建立映射) 5.通过需要加密的字符串通过映射表查询对应的结果
#华为OD#
查看14道真题和解析
