8题解 | #字符串加密#
字符串加密
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); String key = in.nextLine(); String plaintext = in.nextLine(); Set<Character> chset = new LinkedHashSet<>(); // 去重并且保证顺序 char [] keyArr = key.toCharArray(); for(int i = 0;i<keyArr.length;i++){ chset.add(Character.toLowerCase(keyArr[i])); } Iterator it = chset.iterator(); LinkedHashSet<Character> lset = new LinkedHashSet<>(); lset.addAll(Arrays.asList('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')); // 先缓存单词字母,然后移除变化的字母 List<Character> charList = new ArrayList<>(); char[] upperKeychar = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; char[] lowerKeychar = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; while(it.hasNext()){ Character aaa = (Character)it.next(); charList.add(aaa); lset.remove(aaa); } // System.out.println(charList.toString()); // System.out.println(lset); charList.addAll(lset); // System.out.println(Arrays.toString(upperKeychar)); // System.out.println(charList.toString()); Map<Character,Character> resultLowermap = new LinkedHashMap<>(); Map<Character,Character> resultUppermap = new LinkedHashMap<>(); // 存放加密映射 for(int i = 0;i<26;i++){ resultLowermap.put(lowerKeychar[i],charList.get(i)); resultUppermap.put(upperKeychar[i],Character.toUpperCase(charList.get(i))); } // 对数据进行加密处理 StringBuilder sb = new StringBuilder(); for(int i = 0;i<plaintext.length();i++){ char ch = plaintext.charAt(i); if(Character.isLowerCase(ch)){ sb.append(resultLowermap.get(ch)); }else if(Character.isUpperCase(ch)){ sb.append(resultUppermap.get(ch)); }else{ sb.append(plaintext.charAt(i)); } } System.out.println(sb.toString()); } }