题解 | #字符串加密#
字符串加密
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); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String key = in.nextLine(); String encodeStr = in.nextLine(); //key去重 Set<Character> keySet = new LinkedHashSet<>(); //标准字母表与新字母表的对应关系map Map<Character, Character> standardAndNewMap = new LinkedHashMap<>(); char start = 'a'; String newKey = ""; for (int i = 0; i < key.length(); i++) { char ch = key.charAt(i); //set中没有,给予保留 if (!keySet.contains(ch)) { newKey += ch; keySet.add(ch); standardAndNewMap.put(start, ch); start++; } } //基于newKey构建完整的新字母表 for (char ch = 'a'; ch <= 'z'; ch++) { //字母表中的字母不在密匙中,按序加到密匙尾部 if (!keySet.contains(ch)) { standardAndNewMap.put(start, ch); start++; } } //根据信息字符串,获取加密字符串(保留大小写) String result = ""; for (int i = 0; i < encodeStr.length(); i++) { char ch = encodeStr.charAt(i); char temp=ch; //如果是大写,先转成小写,获取加密字符,再将加密字符大写 if (temp >= 'A' && temp <= 'Z') { ch += 32; } //获取加密字符 char secret = standardAndNewMap.get(ch); if (temp >= 'A' && temp <= 'Z') { //加密字符大写 secret-=32; } //拼接结果 result+=secret; } System.out.println(result); } } }
没有评估,后面再看。去重、构建标准表和新表的对应关系(小写)、根据要加密的信息获取加密字符(大小写保留)。