题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
String toEncode=sc.nextLine();
String toDecode=sc.nextLine();
String encoded = encode(toEncode);
System.out.println(encoded);
String decoded = decode(toDecode);
System.out.println(decoded);
}
private static String encode(String toEncode){
char[] encoded = new char[toEncode.length()];
for(int i=0;i<toEncode.length();i++){
char c=toEncode.charAt(i);
if(c>='a'&&c<='z'){
encoded[i]=(char)((c-'a'+1)%26+'A');
}else if(c>='A'&&c<='Z'){
encoded[i]=(char)((c-'A'+1)%26+'a');
}else if(c>='0'&&c<='9'){
encoded[i]=(char)((c-'0'+1)%10+'0');
}
}
return new String(encoded);
}
private static String decode(String toDecode){
char[] decoded = new char[toDecode.length()];
for(int i=0;i<toDecode.length();i++){
char c=toDecode.charAt(i);
// 注意边界
if(c=='a'){
decoded[i]='Z';
}else if(c=='A'){
decoded[i]='z';
}else if(c=='0'){
decoded[i]='9';
}else if(c>'a'&&c<='z'){
decoded[i]=(char)((c-'a'-1)%26+'A');
}else if(c>'A'&&c<='Z'){
decoded[i]=(char)((c-'A'-1)%26+'a');
}else if(c>'0'&&c<='9'){
decoded[i]=(char)((c-'0'-1)%10+'0');
}
}
return new String(decoded);
}
}