题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static String ABC = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { Scanner in = new Scanner(System.in); String key = in.nextLine(); String words = build(key); //利用ABC字母表和key秘钥构建新字母表words Map<Character,Character> map = new TreeMap<>(); for(int i=0; i<ABC.length(); i++){ map.put(ABC.charAt(i), words.charAt(i)); //上行:ABC字母表 下行:words新字母表 } String str = in.nextLine(); String res = encode(str, map); System.out.println(res); } private static String build(String s){ //字符串字母去重 StringBuffer sb = new StringBuffer(); for(int i=0; i<s.length(); i++){ char c = s.charAt(i); if(sb.indexOf(String.valueOf(c)) == -1) sb.append(c); } s = sb.toString(); //26字母去s重 StringBuffer sb2 = new StringBuffer(); for(int i=0; i<ABC.length(); i++){ char c2 = ABC.charAt(i); if(!s.contains(String.valueOf(c2))) sb2.append(c2); } String temp = sb2.toString(); //s拼接去重后“26字母” return s + temp; } private static String encode(String s, Map<Character, Character> map){ //注意:被加密s中字符的大小写顺序保持不变 //s作为查找key,获取map中对应的value StringBuffer sb = new StringBuffer(); for(int i=0; i<s.length(); i++){ char k = s.charAt(i); if(Character.isUpperCase(k)){ k = Character.toLowerCase(k); char v = map.get(k); sb.append(Character.toUpperCase(v)); }else if(Character.isLowerCase(k)){ sb.append(map.get(k)); }else { sb.append(k); //空格 } } return sb.toString(); } }