题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*;
public class HJ36 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String key = in.nextLine();
String toEncrypt = in.nextLine();
String encryptedStr = encrypt(key, toEncrypt);
System.out.println(encryptedStr);
}
}
public static String encrypt(String key, String toEncrypt) {
// 初始字典表
Character[] keyTable = initKeyTable(key);
StringBuilder result = new StringBuilder(toEncrypt.length());
for (Character ch : toEncrypt.toCharArray()) {
result.append(keyTable[Character.toLowerCase(ch) - 'a']);
}
return result.toString();
}
/**
* 生成密钥表
*
* @param key 密钥
* @return 密钥表
*/
public static Character[] initKeyTable(String key) {
Character[] keyTable = new Character[26];
String keyLowerCase = key.toLowerCase(Locale.ROOT);
Set<Character> addedKeys = new LinkedHashSet<>(26);
// 先添加本字符串key
for (Character ch : keyLowerCase.toCharArray()) {
addedKeys.add(ch);
}
// 添加其余字符
for (char i = 'a'; i <= 'z'; i++) {
addedKeys.add(i);
}
addedKeys.toArray(keyTable);
return keyTable;
}
}