列表

详情


面试题 16.20. T9键盘

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

示例 1:

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

示例 2:

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

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: vector<string> getValidT9Words(string num, vector<string>& words) { } };

python3 解法, 执行用时: 40 ms, 内存消耗: 16.5 MB, 提交时间: 2022-11-17 22:43:53

string = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
DICT = {}
for i in range(2, 10):
    for w in string[i-2]:
        DICT[w] = str(i)


class Solution:
    def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
        def check(va):
            for j, x in enumerate(num):
                if DICT[va[j]] != x:
                    return False
            return True

        return [word for word in words if check(word)]

python3 解法, 执行用时: 48 ms, 内存消耗: 16.4 MB, 提交时间: 2022-11-17 22:38:59

class Solution:
    def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
        dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        return [word for word in words if all(char in dic[num[idx]] for idx, char in enumerate(word))]

上一题