题目:

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

程序员面试金典-面试题 16.20. T9键盘

示例 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 这两个数字

分析:

遍历字符串数组中的每一个单词的每一个字符,检查其是否在对应的数字键对应的字符中出现,如果都符合,就将单词加入到结果集中。

利用String.indexOf()来判断是否在字符中,如果在则返回对应的索引,不在返回-1.

程序:

class Solution {
    public List<String> getValidT9Words(String num, String[] words) {
        List<String> res = new ArrayList<>();
        for(String word:words){
            boolean flag = true;
            for(int i = 0; i < word.length(); ++i){
                if(keys[num.charAt(i) - '0'].indexOf(word.charAt(i)) == -1){
                    flag = false;
                    break;
                }
            }
            if(flag)
                res.add(word);
        }
        return res;
    }
    private String[] keys =  {"","!@#","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
}

 

相关文章:

  • 2021-11-14
  • 2021-10-18
  • 2021-05-22
  • 2022-01-20
  • 2021-06-06
  • 2021-05-30
  • 2022-02-28
  • 2021-05-23
猜你喜欢
  • 2021-08-21
  • 2021-12-12
  • 2021-12-31
  • 2021-09-21
  • 2021-07-06
  • 2021-11-06
  • 2022-01-29
相关资源
相似解决方案