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:
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 my solution
思路:如果一个单词的字母全在键盘的某一行,那个这个单词的set和某一行的交集就是这个set的length
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
if not words:return []
line_1 = "qwertyueiop"
line_2 = "asdfghjkl"
line_3 = "zxcvbnm"
row = []
for word in words:
wordset = set(word.lower())
length = len(wordset)
if len(wordset.intersection(line_1))== length or len(wordset.intersection(line_2)) == length or len(wordset.intersection(line_3)) == length:
row.append(word)
return row
2 记录一个discussion里的solution
使用all和any 感觉还蛮有趣的
all(iterable):"有‘假’为False,全‘真’为True,iterable为空是True"
any(iterable):"有‘真’为True,全‘假’为False,iterable为空是False"
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
return [word for word in words if all([all([char in line for char in word.lower()])==any([char in line for char in word.lower()]) for line in ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']])]