给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

示例1:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
注意:
- 你可以重复使用键盘上同一字符。
- 你可以假设输入的字符串将只包含字母。
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
firstLine="qwertyuiop"
secondeLine="asdfghjkl"
thirdLine="zxcvbnm"
results=[]
for string in words:
infirst = True
inSecond = True
inThird = True
string2 = string.lower()
# 先与第一行判断
for s in string2:
if s in firstLine:
continue
else:
infirst = False
break
if infirst:
results.append(string)
continue
# 与第二行判断
for s in string2:
if s in secondeLine:
continue
else:
inSecond = False
break
if inSecond:
results.append(string)
continue
# 与第三行判断
for s in string2:
if s in thirdLine:
continue
else:
inThird = False
break
if inThird:
results.append(string)
return results
本文介绍了一种算法,该算法接收一个单词列表作为输入,并筛选出仅使用键盘同一行字母组成的单词。通过逐行比较每个单词与键盘布局,实现高效筛选。
447

被折叠的 条评论
为什么被折叠?



