题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*; import java.lang.*; // 注意类名必须为 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 a = in.nextLine();//取密钥单词串 String p = in.nextLine();//取要加密的原文 //将密钥单词去重并小写后放入字符串构造器 StringBuilder sb =new StringBuilder(); for(int i=0;i<a.length();i++){ char ci = Character.toLowerCase(a.charAt(i)); String si = String.valueOf(ci); if(!sb.toString().contains(si)){ sb.append(si); } } //生产26个顺序小写英文字母的字符串;生成密钥字符串(长度也是26) String s26=""; for(int j=0;j<26;j++){ char cj=(char)('a'+j); String sj = Character.toString(cj); if(!sb.toString().contains(sj)){ sb.append(sj); } s26=s26.concat(sj); } String s = sb.toString(); char[] cs26 = s26.toCharArray(); //对照顺序字母串找出原文中各个字母的下标,从密钥串中取要替换的字母并保留大小写状态 String pout =""; for(int k=0;k<p.length();k++){ char pk= p.charAt(k); boolean islow=Character.isLowerCase(pk); int index=Arrays.binarySearch(cs26,Character.toLowerCase(pk)); char pko = s.charAt(index); if(!islow){ pko=Character.toUpperCase(pko); } pout=pout.concat(Character.toString(pko)); } System.out.println(pout); } } }