题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
1.先用set保存key的char
2.然后a到z继续插入
3.用数组转存
4。下标映射
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String key = ""; String text = ""; while(in.hasNextLine()){ key = in.nextLine(); text =in.nextLine(); String result = encrypt(text,key); System.out.println(result); } } static String encrypt(String text,String key) { LinkedHashSet<Character> set = new LinkedHashSet<>(); for(char c : key.toCharArray()){ set.add(c); } for(char c = 'a';c<='z';c++){ set.add(c); } int k = 0; char[] arr = new char[26]; for(Character c:set){ arr[k++] = c; } StringBuffer sb = new StringBuffer(); for(char c :text.toCharArray()){ if (c >= 'a'){ sb.append(arr[c - 'a']); } else { sb.append(arr[c - 'A' + 'a'] - 'a' +'A'); } } return sb.toString(); } }