题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.Scanner; import java.util.LinkedHashSet; import java.util.HashMap; import java.util.ArrayList; import java.io.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException{ // Scanner in = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //加密方法 String str1 = in.readLine(); //需要加密的字符串 String str2 = in.readLine(); int[] count = new int[26]; char[] chars1 = str1.toCharArray(); char[] chars2 = str2.toCharArray(); //对chars1去重 LinkedHashSet<Character> set = new LinkedHashSet<Character>(); for(int i=0;i<chars1.length;i++){ set.add(chars1[i]); } //把set补成一个新的字符表 //同时下标对应的就是原字母表 int n=0; while(set.size()<26){ char c = (char)('a'+n); set.add(c); n++; } //构建一个hashMap //HashMap<Character,Character> map = new HashMap<>(); //建立一个list集合把set集合放进去 ArrayList<Character> list = new ArrayList<>(set); //开始加密 StringBuilder sb = new StringBuilder(); for(int i=0;i<chars2.length;i++){ if(chars2==null){ sb.append(chars2[i]); }else{ int index = (chars2[i]-'a'); sb.append(list.get(index)); } } System.out.print(sb.toString()); } }