当前位置:   article > 正文

[python]:T9键盘_micropython t9输入

micropython t9输入

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



示例 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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

一、常规法
遍历words与num一一对比

class Solution:
    def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
        table = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        return list(filter(lambda word: all(ch in table[key] for key, ch in zip(num, word)), words))
  • 1
  • 2
  • 3
  • 4

二、正则表达

class Solution:
    def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
        pattern = ["[a-c]", "[d-f]", "[g-i]", "[j-l]", "[m-o]", "[p-s]", "[t-v]", "[w-z]"]
        lnum = len(num)
        sb = ""
        for i in range(lnum):
            sb += pattern[int(num[i])-2]
        res = []
        for word in words:
           if re.match(sb, word):
               res.append(word)
        return res
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/384026
推荐阅读
相关标签
  

闽ICP备14008679号