题号:no80
题目名:T9键盘
原题URL:https://leetcode-cn.com/problems/t9-lcci/
题目描述
在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。
示例
示例 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 这两个数字
思路
1.直接遍历word,看是否匹配数字
2.核心是需要做一个数字表去映射字母
解题代码
public class Solution {
public List<String> getValidT9Words(String num, String[] words) {
List<String> res = new ArrayList<>();
//创建映射表
int[] hash = {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};
//遍历word
for (int i = 0; i < words.length; i++) {
boolean isMatch = true;
//看是否完全匹配num,如果匹配就加入
for (int j = 0; j < words[i].length(); j++) {
if(num.charAt(j)-'0'!=hash[words[i].charAt(j)-'a']) {
isMatch = false;
break;
}
}
if(isMatch) res.add(words[i]);
}
return res;
}
}