题解 | #字符串加密#哈希
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String secret = in.nextLine();
Map<Character, Character> dictionary = getDictionary(secret);
String text = in.nextLine();
text = encrypt(text, dictionary);
System.out.println(text);
}
private static Map<Character, Character> getDictionary(String secret) {
// 去重
LinkedHashSet<Character> set = new LinkedHashSet<>();
for (int i = 0; i < secret.length(); i++) {
set.add(secret.charAt(i));
}
// 加密替换
HashMap<Character, Character> map = new HashMap<>();
Iterator<Character> iterator = set.iterator();
char value = 'a';
for (int i = 0; i < 26; i++) {
char key = (char) ('a' + i);
if (iterator.hasNext()) {
map.put(key, iterator.next());
} else {
while (set.contains(value) && value <= 'z') {
++value;
}
map.put(key, value);
value++;
}
}
return map;
}
private static String encrypt(String text,
Map<Character, Character> dictionary) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (dictionary.containsKey(c)) {
builder.append(dictionary.get(c));
} else {
builder.append(c);
}
}
return builder.toString();
}
}

查看17道真题和解析