题解 | #简单密码#

简单密码

https://www.nowcoder.com/practice/7960b5038a2142a18e27e4c733855dac

用 Map 存储字符,能够有效检查 if else 条件地狱,稍微花点钱(内存)可以有效提高代码清晰度。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // 创建字符到数字的映射表
        Map<Character, Character> map = new HashMap<>();
        map.put('a', '2');
        map.put('b', '2');
        map.put('c', '2');
        map.put('d', '3');
        map.put('e', '3');
        map.put('f', '3');
        map.put('g', '4');
        map.put('h', '4');
        map.put('i', '4');
        map.put('j', '5');
        map.put('k', '5');
        map.put('l', '5');
        map.put('m', '6');
        map.put('n', '6');
        map.put('o', '6');
        map.put('p', '7');
        map.put('q', '7');
        map.put('r', '7');
        map.put('s', '7');
        map.put('t', '8');
        map.put('u', '8');
        map.put('v', '8');
        map.put('w', '9');
        map.put('x', '9');
        map.put('y', '9');
        map.put('z', '9');
        map.put('0', '0');
        map.put('1', '1');
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            // int a = in.nextInt();
            // int b = in.nextInt();
            // System.out.println(a + b);
            String input = in.nextLine();
            char[] chars = input.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char ch = chars[i];
                if (map.containsKey(ch)) {
                    chars[i] = map.get(ch);
                } else if (ch >= 'A' && ch < 'Z') {
                    chars[i] = (char)(ch - 'A' + 'b');
                } else if (ch == 'Z') {
                    chars[i] = 'a';
                }
                System.out.print(chars[i]);
            }
        }
    }
}

全部评论

相关推荐

重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务