题解 | #字符串加解密#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String s1 = scan.nextLine();
String s2 = scan.nextLine();
String res1 = encrypt(s1);
String res2 = decrypt(s2);
System.out.println(res1);
System.out.println(res2);
}
}
//加密
public static String encrypt(String s) {
StringBuffer res = new StringBuffer();
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if (c >= '0' && c <= '9') {
if (c == '9') res.append(0);
else res.append(c - '0' + 1);
} else if (c >= 'a' && c <= 'z') {
if (c == 'z') res.append('A');
else res.append((char) (c - 'a' + 'B'));
} else {
if (c == 'Z') res.append('a');
else res.append((char) (c - 'A' + 'b'));
}
}
return res.toString();
}
//解密
public static String decrypt(String s) {
StringBuffer res = new StringBuffer();
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if (c >= '0' && c <= '9') {
if (c == '0') res.append(9);
else res.append(c - '0' - 1);
}else if (c >= 'a' && c <= 'z') {
if (c == 'a') res.append("Z");
else res.append((char) (c - 'a' + 'A' - 1));
}else {
if (c == 'A') res.append('z');
else res.append((char) (c - 'A' + 'a' - 1));
}
}
return res.toString();
}
}