题目Description###
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:####
白痴思维,大致就是看word是否只属于某一行。
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
list1 = ['qwertyuiopQWERTYUIOP']
list2 = ['asdfghjklASDFGHJKL']
list3 = ['ZXCVBNMzxcvbnm']
rList = []
i = 0
while( i< len(words) ):
if words[i] <= list1 or words[i] <= list2 or words[i] <= list3:
rList.append(words[i])
else:
continue
i=i+1
return rList
```
结果:超时
![](http://upload-images.jianshu.io/upload_images/395849-e862c0b1d0dc65cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
为什么会超时呢?
####思路2:####
利用set的属性,然而还是超时。
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
row1 = set('qwertyuiopQWERTYUIOP')
row2 = set('asdfghjklASDFGHJKL')
row3 = set('zxcvbnmZXCVBNM')
rList = []
i = 0
while( i< len(words) ):
x = set(words[i])
if x.issubset(row1) or x.issubset(row2) or x.issubset(row3):
rList.append(words[i])
else:
continue
i=i+1
return rList
结果:
![](http://upload-images.jianshu.io/upload_images/395849-19efc5eaa6a9f083.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
为什么会超时呢?
####思路3:####
参考discuss中**hotea**的方法,使用filter和匿名函数。
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
row1 = set('qwertyuiopQWERTYUIOP')
row2 = set('asdfghjklASDFGHJKL')
row3 = set('zxcvbnmZXCVBNM')
return filter(lambda x: set(x).issubset(row1) or set(x).issubset(row2) or set(x).issubset(row3), words)