题目
难度:★★☆☆☆
类型:数组
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
键盘
注意
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
示例
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
解答
我们将问题分解:
对列表中所有单词判别 =》 每一个单词中的字符在键盘上是否是同一行
对每一个单词的判别 =》所有字符在键盘上的行号是否相同
这里我们编码时这样实现:
构建字符-行号字典,表达字符与行号之间的关系;
构建单词判别函数,用于判断单词中的字符的行号是否相同;
使用列表推导式或过滤器对所有单词进行判断。
class Solution:
def findWords(self, words):
# 构造键盘字母-行号字典
position_dict = {'a': 'middle',
'b': 'bottom',
'c': 'bottom',
'd': 'middle',
'e': 'top',
'f': 'middle',
'g': 'middle',
'h': 'middle',
'i': 'top',
'j': 'middle',
'k': 'middle',
'l': 'middle',
'm': 'bottom',
'n': 'bottom',
'o': 'top',
'p': 'top',
'q': 'top',
'r': 'top',
's': 'middle',
't': 'top',
'u': 'top',
'v': 'bottom',
'w': 'top',
'x': 'bottom',
'y': 'top',
'z': 'bottom',
}
def the_same_row(s):
"""
判断某个字符串中的所有字符是否在键盘上同一行
:param s:
:return:
"""
s = s.lower() # 输入字符串转为小写
first_char_pos = position_dict[s[0]] # 第一个字符的行号
for c in s[1:]: # 遍历剩下的字符
if not position_dict[c] == first_char_pos: # 如果存在字符和第一个字符不在同一行
return False # False
return True # 所有字符都在同一行
return [s for s in words if the_same_row(s)] # 对每个单词进行判别,组成新列表
# return list(filter(the_same_row, words)) # 也可以使用过滤器减小内存开销
如有疑问或建议,欢迎评论区留言~