【华为OD机考】九宫格按键输入法

题目描述: 九宫格按键输入,判断输出,有英文和数字两个模式,默认是数字模式。

数字模式直接输出数字,英文模式连续按同一个按键会依次出现这个按键上的字母,如果输入"/"或者其他字符,则循环中断。

九宫格键盘布局如下
1(,.) 2(abc)3(def)
4(ghi)5(jkl)6(mno)
7(pqrs)8(tuv)9(wxyz)
0(空格) # /
输入描述: 要求输入一串按键,输出屏幕显示输入描述:输入范围为数字0~9和字符'#'、’/’

输出屏幕显示:
例如,
在数字模式下,输入1234,显示1234
在英文模式下,输入1234,显示,adg

输出描述:
1、#用于切换模式,默认是数字模式,执行#后切换为英文模式;
2、/表示延迟,例如在英文模式下,输入22/222,显示为bc;
3、英文模式下,多次按同一键,例如输入22222,显示为b;

测了几组demo没发现问题,仅供参考:

public class 九宫格输入法 {
    public static Map<Character,String[]> keyBoards = new HashMap<>();

    static {
        keyBoards.put('1',new String[] {",","."});
        keyBoards.put('2',new String[] {"a","b","c"});
        keyBoards.put('3',new String[] {"d","e","f"});
        keyBoards.put('4',new String[] {"g","h","i"});
        keyBoards.put('5',new String[] {"j","k","l"});
        keyBoards.put('6',new String[] {"m","n","o"});
        keyBoards.put('7',new String[] {"p","q","r","s"});
        keyBoards.put('8',new String[] {"t","u","v"});
        keyBoards.put('9',new String[] {"w","x","y","z"});
        keyBoards.put('0',new String[] {" "});
    }

    public static void main(String[] args) {
        System.out.println(printKeyBoard("#/22/2022#33#872233444/44"));
    }

    public static String printKeyBoard(String command) {
        if(command.length() == 0) {
            return "";
        }

        int mod = 0; // 输入模式: 0-数字 1-字符
        char[] cs = command.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<cs.length;i++) {
            if(cs[i] == '#') {
                mod = mod == 0 ? 1 : 0;
            } else if(mod == 1 && Character.isDigit(cs[i])){
                 // #2223/2
                 int num = 1;
                 for(int j=i;j<cs.length;j++) {
                     if(j+1<cs.length && cs[j] == cs[j+1]) {
                         num++;
                         i=j+1;
                     } else {
                         break;
                     }
                 }
                 String curStr = keyBoards.get(cs[i])[(num-1)%keyBoards.get(cs[i]).length];
                 sb.append(curStr);
            } else if(mod == 0 && Character.isDigit(cs[i])) {
                sb.append(cs[i]);
            }
        }

        return sb.toString();
    }
}
全部评论
这是100分还是200分的题啊
点赞 回复 分享
发布于 2022-06-28 21:11

相关推荐

河和静子:如果大专也能好过的话,我寒窗苦读几年的书不是白读了?
点赞 评论 收藏
分享
评论
3
7
分享
牛客网
牛客企业服务