题目
给定一个单词列表,返回只能在一行美式键盘上使用字母输入的单词。
判断给出的单词列表能否给一个美式键盘的一行字母输入完成。
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
我的代码
题目难度很低。即添加几个set判断字母有没有在set中即可。
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
set1=set("qwertyuiopQWERTYUIOP")
set2=set("asdfghjklASDFGHJKL")
set3=set("zxcvbnmZXCVBNM")
ans=[]
for word in words:
sign =True
for c in word:
if c not in set1:
sign=False
if sign:
ans.append(word)
for word in words:
sign =True
for c in word:
if c not in set2:
sign=False
if sign:
ans.append(word)
for word in words:
sign =True
for c in word:
if c not in set3:
sign=False
if sign:
ans.append(word)
return ans
优秀代码
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
d1={'q','w','e','r','t','y','u','i','o','p'}
d2={'a','s','d','f','g','h','j','k','l'}
d3={'z','x','c','v','b','n','m'}
l=[]
r=[]
for i in words:
l.append(i.lower())
for i in range(len(l)):
a=[0,0,0]
for j in l[i]:
if j in d1:
a[0]=1
if j in d2:
a[1]=1
if j in d3:
a[2]=1
if a.count(1)==1:
r.append(words[i])
return r