在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到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 这两个数字
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<String> getValidT9Words(String num, String[] words) {
char[][] charMap = {{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'}, {'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}};
List<String> result = new ArrayList<>();
for (String word : words) {
if (num.length() != word.length()) {
continue;
}
boolean isValid = true;
for (int i = 0; i < num.length(); i++) {
char ch = word.charAt(i);
char numCh = num.charAt(i);
boolean isMatch = false;
char[] charArr = charMap[numCh - '2'];
for (char c : charArr) {
if (c == ch) {
isMatch = true;
break;
}
}
if (!isMatch) {
isValid = false;
break;
}
}
if (isValid) {
result.add(word);
}
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)