题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String str = br.readLine(); char[] chars = str.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < 26; i++) { map.put((char)(i + 65), i + 65); } for (int i = 0; i < 26; i++) { map.put((char)(i + 97), i + 97); } for (int i = 0; i < 10; i++) { map.put((i + "").charAt(0), i); } StringBuffer sb = new StringBuffer(); //加密 for (char c : chars) { Integer index = map.get(c); if (index != null) { if (index == (65 + 25)) { index = 65; } else if (index == 97 + 25) { index = 97; } else if (index == 9) { index = 0; } else { index++; } if (index >= 0 && index <= 9) { sb.append(index); } else if (c >= 'a' && c <= 'z') { sb.append((char)(index.intValue() - 32)); } else { sb.append((char)(index.intValue() + 32)); } } else { sb.append(c); } } System.out.println(sb.toString()); //解密 str = br.readLine(); sb.setLength(0); chars = str.toCharArray(); for (char c : chars) { Integer index = map.get(c); if (index != null) { if (index == 65) { index = 65 + 25; } else if (index == 97) { index = 97 + 25; } else if (index == 0) { index = 9; } else { index--; } if (index >= 0 && index <= 9) { sb.append(index); } else if (c >= 'a' && c <= 'z') { sb.append((char)(index.intValue() - 32)); } else { sb.append((char)(index.intValue() + 32)); } } else { sb.append(c); } } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } }