题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = sc.next(); String password = sc.next(); Set<Character> set = new LinkedHashSet<>(); for (int i = 0; i < key.length(); i++) { set.add(key.charAt(i)); } Map<Character, Character> dic = new HashMap<>(); // 记录密钥 int i = 0; for (Character ch : set) { char plain = (char) ('a' + i); dic.put(plain, ch); i++; } // 记录剩余的字母 Set<Character> set1 = new LinkedHashSet<>(); for (int j = 0; j < 26; j++) { char ch = (char) ('a' + j); if (!set.contains(ch)) { set1.add(ch); } } // 密文配对 for (Character ch : set1) { char plain = (char) ('a' + i); dic.put(plain, ch); i++; } StringBuilder ans = new StringBuilder(); for (int j = 0; j < password.length(); j++) { ans.append(dic.get(password.charAt(j))); } System.out.println(ans); } }