题解 | #字符串加解密#

字符串加解密

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);
        int size = 26;
        int nSize = 10;
        char[] lowArray = new char[size];
        char[] upArray = new char[size];
        char[]numArray = new char[nSize];
        char l = 'a';
        char u = 'A';
        char o = '0';
        for (int i = 0; i < 26; i++) {
            lowArray[i] = l++;
            upArray[i] = u++;
            if (i < nSize) {
                numArray[i] = o++;
            }
        }
        while (in.hasNext()) {
            String code = in.nextLine();
            String decode = in.nextLine();

            //加密
            char[] codeArray = code.toCharArray();
            StringBuilder sb = new StringBuilder(code.length());
            for (char c : codeArray) {
                if ('a' <= c && c <= 'z') {
                    int index = c - 'a' + 1;//后移一位
                    char t = upArray[index % size];
                    sb.append(t);
                    continue;
                }
                if ('A' <= c && c <= 'Z') {
                    int index = c - 'A' + 1;//后移一位
                    char t = lowArray[index % size];
                    sb.append(t);
                    continue;
                }
                if ('0' <= c && c <= '9') {
                    int index = c - '0' + 1;
                    char t = numArray[index % nSize];
                    sb.append(t);
                    continue;
                }
                sb.append(c);
            }
            System.out.println(sb.toString());

            //解密
            char[] decodeArray = decode.toCharArray();
            StringBuilder sb2 = new StringBuilder(decode.length());
            for (char c : decodeArray) {
                if ('a' <= c && c <= 'z') {
                    int index = c - 'a' + size -1; //前移一位 避免负值 统一 +size 再取模
                    char t = upArray[index % size];
                    sb2.append(t);
                    continue;
                }
                if ('A' <= c && c <= 'Z') {
                    int index = c - 'A' + size - 1; //前移一位
                    char t = lowArray[index % size];
                    sb2.append(t);
                    continue;
                }
                if ('0' <= c && c <= '9') {
                    int index = c - '0' + nSize - 1;
                    char t = numArray[index % nSize];
                    sb2.append(t);
                    continue;
                }
                sb2.append(c);
            }
            System.out.println(sb2.toString());
        }
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务