Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Example 1:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
1、简短的答案 any 和 all
主要用到了python中的all和any函数,所以整个过程非常简单
class Solution(object):
def findWords(self, words):
l=['qwertyuiop','asdfghjkl','zxcvbnm']
res=[]
for w in words:
if any(all(c in ll for c in w.lower()) for ll in l): # Exists(ll in l) ForAny(c in w) SuchThat(c in ll)
res.append(w)
return res
2、集合解法1 issubset()
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
row1 = set('qwertyuiop')
row2 = set('asdfghjkl')
row3 = set('zxcvbnm')
res = []
for each in words:
target = set(each.lower())
if target.issubset(row1) or target.issubset(row2) or target.issubset(row3):
res.append(each)
return res
3、集合解法2
myList = list()
for word in words:
a = {'q','w','e','r','t','y','u','i','o','p'}
b = {'a','s','d','f','g','h','j','k','l'}
c = {'z','x','c','v','b','n','m'}
myBool = True
for letter in word:
if letter.lower() in a:
b = a
c = a
elif letter.lower() in b:
a = b
c = b
elif letter.lower() in c:
a = c
b = c
else:
myBool = False
if myBool == True:
myList.append(word)
return myList
4、我的答案
class Solution:
def findWords(self, words):
result=[]
def isinstr(keys,word1):
flag=True
for alpha in word1:
if alpha not in keys:
flag=False
break
return flag
keylist=['asdfghjkl','qwertyuiop','zxcvbnm']
for word in words:
word1=word.lower()
for keys in keylist:
if word1[0] in keys:
if isinstr(keys,word1):
result.append(word)
break
return result