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.
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.

Example:
- Input: ["Hello", "Alaska", "Dad", "Peace"]
- Output: ["Alaska", "Dad"]
Python Solution 1:
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
res = []
flags = {
'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1,
'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2,
'z': 4, 'x': 4, 'c': 4, 'v': 4, 'b': 4, 'n': 4, 'm': 4
}
for word in words:
flag = flags[word[0].lower()]
for c in word:
if flags[c.lower()] != flag:
flag = 0
break
if flag: res.append(word)
return res
Python Solution 2:
def findWords(self, words):
return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)
Summary:
- Solution 1's code style is similar to C. I care too much about efficiency.
- Solution 2 is much more pythonic.
LeetCode: 500. Keyboard Row





近期评论