Keyboard Row
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.
解题思路:
集合运算
判断输入单词的字母集合是否为键盘某一行字母集合的子集
useset
to check the word.First make every line a set of letter.Then I check every word if this word set is the subset if any line set.
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
result = []
for word in words:
w = set(word.lower())
if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
result.append(word)
return result
set 的issubset()
s.issubset(t) 与 s <= t 相等:test whether every element in s is in t。
Last updated
Was this helpful?