题解 | #字符串加密#
字符串加密
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);
while (in.hasNext()) {
// 密钥
String key = in.nextLine();
// 明文
String pwd = in.nextLine();
// 有序去重
Set<Character> set = new LinkedHashSet<>();
for (int i = 0; i < key.length(); i++) {
set.add(key.charAt(i));
}
// 补全字母
for (int i = 0; i < 26; i++) {
set.add((char)('a' + i));
}
// 集合转列表
List<Character> list = new ArrayList<>(set);
// 加密
StringBuilder s = new StringBuilder();
for (int i = 0; i < pwd.length(); i++) {
if (pwd.charAt(i) == ' ') {
s.append(pwd.charAt(i));
} else {
int index = Integer.valueOf(pwd.charAt(i) - 'a');
s.append(list.get(index));
}
}
System.out.println(s);
}
}
}
查看2道真题和解析