【题目描述】
在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示:
https://leetcode.cn/problems/t9-lcci/
【示例】
【代码】解析几何
巧妙的:利用字符来获取数字确保唯一性(多对一)
package com.company;
// 2022-02-07
import java.util.*;
class Solution {
public List<String> getValidT9Words(String num, String[] words) {
HashMap<Character, Character> map = new HashMap<>(26);
map.put('a', '2');
map.put('b', '2');
map.put('c', '2');
map.put('d', '3');
map.put('e', '3');
map.put('f', '3');
map.put('g', '4');
map.put('h', '4');
map.put('i', '4');
map.put('j', '5');
map.put('k', '5');
map.put('l', '5');
map.put('m', '6');
map.put('n', '6');
map.put('o', '6');
map.put('p', '7');
map.put('q', '7');
map.put('r', '7');
map.put('s', '7');
map.put('t', '8');
map.put('u', '8');
map.put('v', '8');
map.put('w', '9');
map.put('x', '9');
map.put('y', '9');
map.put('z', '9');
LinkedList<String> res = new LinkedList<>();
int len = words.length;
for (int i = 0; i < len; i++){
String word = words[i];
int idx = 0;
for (int j = 0; j < word.length(); j++){
char c = word.charAt(j);
if (map.get(c) != num.charAt(idx++)){
break;
}
if (j == word.length() - 1){
res.addLast(word);
}
}
}
System.out.println(res);
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().getValidT9Words( "8733", new String[]{"tree", "used"}); // 输出:2
new Solution().getValidT9Words("2", new String[]{"a", "b", "c", "d"}); // 输出:1
}
}