题解 | #字符串加密#
字符串加密
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 key = in.next(); String str = in.next(); encStr(key, str); } in.close(); } private static void encStr(String key, String str) { int len1 = key.length(); int len2 = str.length(); int count = 0; // a-z 1代表该字母出现 int[] cmp = new int[26]; // 新顺序字母表 char[] cmp1 = new char[27]; for (int i = 0; i < len1; i++) { if (cmp[key.charAt(i) - 'a'] == 0) { cmp1[count] = key.charAt(i); // 对应位置标记为1 cmp[key.charAt(i) - 'a'] = 1; count++; //秘钥中不重复的字母 } } // 补全剩余新顺序字母表 for (int i = count; i < 26; i++) { for (int j = 0; j < 26; j++) { if (cmp[j] == 0) { cmp[j] = 1; cmp1[i] = (char)('a'+j); break; } } } for (int i = 0; i < len2; i++) { System.out.print(cmp1[str.charAt(i)-'a']); } } }