题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String toEncrypt = in.nextLine(); String toDecrypt = in.nextLine(); System.out.println(Code(toEncrypt, true)); System.out.println(Code(toDecrypt, false)); } private static String Code(String s, boolean encrypt) { String en = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String cp = "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"; String num = "0123456789"; StringBuilder sb = new StringBuilder(); for (char i : s.toCharArray()) { if (encrypt) { if (num.contains(String.valueOf(i))) { int j = num.indexOf(i); if (j >= num.length() - 1) { j = 0; } else { j += 1; } sb.append(num.charAt(j)); } if (en.contains(String.valueOf(i))) { sb.append(cp.charAt(en.indexOf(i))); } } else { if (num.contains(String.valueOf(i))) { int j = num.indexOf(i); if (j == 0) { j = num.length()-1; } else { j -= 1; } sb.append(num.charAt(j)); } if (cp.contains(String.valueOf(i))) { sb.append(en.charAt(cp.indexOf(i))); } } } return sb.toString(); } }
题目有坑。 说是有数字的时候, 其它不变。但其实每个字符都有变。给的示例也不全。