华为机试 HJ21简单密码【java实现】

描述 现在有一种密码变换算法。 九键手机键盘上的数字与字母的对应: 1–1, abc–2, def–3, ghi–4, jkl–5, mno–6, pqrs–7, tuv–8 wxyz–9, 0–0,把密码中出现的小写字母都变成九键键盘对应的数字,如:a 变成 2,x 变成 9. 而密码中出现的大写字母则变成小写之后往后移一位,如:X ,先变成小写,再往后移一位,变成了 y ,例外:Z 往后移是 a 。 数字和其它的符号都不做变换。 数据范围: 输入的字符串长度满足 1≤n≤100
package com.wy.leetcode;

import java.util.Scanner;

/**
 * HJ21 简单密码
 * @author HelloWorld
 * @create 2022/4/18 21:31
 * @email helloworld.dng@gmail.com
 */
public class EasyPassword {
          
   
    /** 秘文 */
    private final static String PRIVATEKEY = "abcdefghijklmnopqrstuvwxyz";
    /** 明文 */
    private final static String PUBLICKEY  = "22233344455566677778889999";

    /** 大写字母规则 */
    private final static String UPPER_LETTER_RULE = "[A-Z]";
    /** 小写字母规则 */
    private final static String LOWER_LETTER_RULE = "[a-z]";

    public static void main(String[] args) {
          
   
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
          
   
            String string = scanner.next();
            String result = "";
            for (int i = 0; i < string.length(); i++) {
          
   
                result += getPublicKey(string.charAt(i) + "");
            }

            System.out.println(result);
        }
    }

    /**
     * @description 加密,将秘文转为明文
     * @author HelloWorld
     * @create 2022/4/18 22:13
     * @param str
     * @return java.lang.String
     */
    private static String getPublicKey(String str) {
          
   
        // 大写字母则变成小写之后往后移一位 Z 往后移是 a
        if (str.matches(UPPER_LETTER_RULE)) {
          
   
            switch (str) {
          
   
                case "Z":
                    return "a";
                default:
                    return (char)(str.toLowerCase().toCharArray()[0] + 1 ) + "";
            }
        }
        // 小写字母都变成九键键盘对应的数字
        if (str.matches(LOWER_LETTER_RULE)) {
          
   
            return PUBLICKEY.charAt(PRIVATEKEY.indexOf(str)) + "";
        }
        // 数字和其他字符
        return str;
    }

}
经验分享 程序员 微信小程序 职场和发展