LeetCode–T9键盘

LeetCode–T9键盘

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

说明

面试题 16.20. T9键盘

题目

在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示:

image-20200808093219722

示例 1:

输入: num = "8733", words = ["tree", "used"]
输出: ["tree", "used"]

示例 2:

输入: num = "2", words = ["a", "b", "c", "d"]
输出: ["a", "b", "c"]

提示

num.length <= 1000
words.length <= 500
words[i].length == num.length
num中不会出现 0, 1 这两个数字

Java

思路

将26个字母按顺序将对应的数字存入数组,再比对输入的数字是否符合

代码
class Solution {
    public List<String> getValidT9Words(String num, String[] words) {
        List<String> res = new ArrayList<>();
        char[] map = {'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','7','7','7','8','8','8','9','9','9','9'};
        for(String word : words){
            int index = 0;
            boolean flag = true;
            for(char c : word.toCharArray()){
                char n = map[c-'a'];
                if(n != num.charAt(index++)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                res.add(word);
            }
        }
        return res;
    }
}

感谢

leetcode

以及勤劳的自己
关注公众号: 归子莫,获取更多的资料,还有更长的学习计划

posted @ 2020-08-08 09:35  归子莫  阅读(1078)  评论(0编辑  收藏  举报
Live2D