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.
这题的意思就是输入一个list,list的元素为字符串,判断每一个字符串能否用键盘上的一行打出来,返回每一个可以的字符串。
我按照题意随便写了一个,感觉比较蠢:
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
list1=['q','w','e','r','t','y','u','i','o','p']
list2=['a','s','d','f','g','h','j','k','l']
list3=['z','x','c','v','b','n','m']
res=[]
a=[1 for n in range(len(words))]
b = [0 for n in range(len(words))]
for i in range(len(words)):
for j in range(len(words[i])):
if words[i][j] in list1:
if b[i]==0 or b[i]==1 :b[i]=1
else: a[i]=0
if words[i][j] in list2:
if b[i]==0 or b[i]==2:b[i]=2
else: a[i]=0
if words[i][j] in list3:
if b[i]==0 or b[i]==3:b[i]=3
else: a[i]=0
for i in range(len(a)):
if a[i]==1:
res.append(words[i])
return res
s=Solution()
s.findWords(['hello','sf','aaaa','qwcd'])
思路就是暴力去求是否能用一行打出,用b数组来记录用哪一行键盘打,如果不止用一行键盘则置a数组对应的元素为0。
当然还有更屌的解法:
def findWords(self, words):
return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)
re.compile:编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
filter()函数:用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。