题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
和题目有所不同, 下面的代码. 支持大小写都存在的用例.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String key = scan.nextLine();
String s = scan.nextLine();
char[] arr = entryption(key);//被加密后的字母顺序
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean isUpper = false;
if (c == ' ') {
sb.append(c);
continue;
}
if (c >= 'A' && c <= 'Z') {
c = (char) (c - 'A' + 'a');
isUpper = true;
}
if (isUpper) sb.append(String.valueOf(arr[c - 'a']).toUpperCase());
else sb.append(arr[c - 'a']);
}
System.out.println(sb.toString());
}
}
public static char[] entryption(String s) {
HashSet<Character> set = new HashSet<>();
List<Character> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') {
c = (char) (c - 'A' + 'a');
}
if (set.contains(c)) continue;
set.add(c);
list.add(c);
}
char[] res = new char[26];
int index = 0;
for (int i = 0; i < list.size(); i++) {
res[index++] = list.get(i);
}
for (int i = (int) 'a'; i <= (int) 'z'; i++) {
char c = (char) i;
if (set.contains(c)) continue;
res[index++] = c;
}
return res;
}
}