題目
難度:★★☆☆☆
類型:數(shù)組
給定一個單詞列表匈辱,只返回可以使用在鍵盤同一行的字母打印出來的單詞。鍵盤如下圖所示杀迹。
鍵盤
注意
你可以重復使用鍵盤上同一字符亡脸。
你可以假設輸入的字符串將只包含字母。
示例
輸入: ["Hello", "Alaska", "Dad", "Peace"]
輸出: ["Alaska", "Dad"]
解答
我們將問題分解:
對列表中所有單詞判別 =》 每一個單詞中的字符在鍵盤上是否是同一行
對每一個單詞的判別 =》所有字符在鍵盤上的行號是否相同
這里我們編碼時這樣實現(xiàn):
構建字符-行號字典树酪,表達字符與行號之間的關系浅碾;
構建單詞判別函數(shù),用于判斷單詞中的字符的行號是否相同续语;
使用列表推導式或過濾器對所有單詞進行判斷垂谢。
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)) # 也可以使用過濾器減小內(nèi)存開銷
如有疑問或建議疮茄,歡迎評論區(qū)留言~