题解 | #简单密码#

简单密码

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

哈希

第一遍自己写的时候用的是 map,相当得丑陋,又臭又长...

import java.util.*;

public class Main {
    private static Map<Character, Integer> map = new HashMap<>();
    
    static {
        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);
    }
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isUpperCase(c)) {
                // 大写则变成小写之后往后移一位
                res.append((char) ((c - 'A' + 1) % 26  + 'a'));
            } else if (Character.isLowerCase(c)) {
                res.append(map.get(c));
            } else {
                res.append(c);
            }
        }
        System.out.println(res);
        in.close();
    }
}

后来参考 大哥题解,意识到可以用 String 来代替 map,会优雅很多

import java.util.*;

public class Main {
    private static final String dict = "22233344455566677778889999";
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isUpperCase(c)) {
                // 大写则变成小写之后往后移一位
                res.append((char) ((c - 'A' + 1) % 26  + 'a'));
            } else if (Character.isLowerCase(c)) {
              	// 小写字母变数字 
                res.append(dict.charAt(c - 'a'));
            } else {
              	// 其他不变
                res.append(c);
            }
        }
        System.out.println(res);
        in.close();
    }
}
全部评论

相关推荐

评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客企业服务