题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String word = in.nextLine(); // 明文 String plaintext = in.nextLine(); char[] secretKey = new char[26]; int[] upperFlag = new int[plaintext.length()]; char[] words = word.toLowerCase().toCharArray(); // 字母是否已存在,下标为字母- 'a' 例如 'a'-'a' = 0,则'a'的下标为0 int[] existFlag = new int[26]; int k = 0; for (int i = 0; i < words.length; i++) { char ch = words[i]; int existFlagIndex = ch - 'a'; // 在单词中已存在此字母,则去除 if (existFlag[existFlagIndex] == 1) { continue; } // 不存在,则标记为已存在 existFlag[existFlagIndex] = 1; // 将字母放入密匙中 secretKey[k] = words[i]; k++; } // 用未出现过的字母,填充密匙字典 for (int i = 0; i < existFlag.length; i++) { if (existFlag[i] == 0) { secretKey[k] = (char) (i + 'a'); k++; } } char[] plaintextChars = plaintext.toCharArray(); for (int i = 0; i < plaintextChars.length; i++) { // 标记大写字母 if (plaintextChars[i] >= 'A' && plaintextChars[i] <= 'Z') { upperFlag[i] = 1; } } StringBuilder codedWord = new StringBuilder(); char[] toCodeChars = plaintext.toLowerCase().toCharArray(); for (int i = 0; i < toCodeChars.length; i++) { char ch = secretKey[toCodeChars[i] - 'a']; // 恢复大写 if (upperFlag[i] == 1) { ch = (char) (ch + 32); } codedWord.append(ch); } System.out.println(codedWord.toString()); } } }