天天看點

華為機試 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 [email protected]
 */
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;
    }

}