归子莫的博客

「笔杆揭不起,绘不出青烟别春泥 ————归子莫」

LeetCode–T9键盘

博客说明

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

说明

面试题 16.20. T9键盘

题目

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

image-20200808093219722

示例 1:

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

示例 2:

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

提示

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

Java

思路

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

代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

以及勤劳的自己

评论