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.

American keyboard

Example 1:

1
2
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.

  2. You may assume the input string will only contain letters of alphabet.

思路

想办法利用简单的数组存储,模仿哈希表,判断一个单词是不是一行键盘就能打出来的【符合题意】。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
ans = []
row = ["QWERTYUIOPqwertyuiop", "ASDFGHJKLasdfghjkl", "ZXCVBNMzxcvbnm"]
for word in words:
append = True
if (word[0] in row[0]):
for i in word:
if (i not in row[0]):
append = False
break
elif (word[0] in row[1]):
for i in word:
if (i not in row[1]):
append = False
break
else:
for i in word:
if (i not in row[2]):
append = False
break
if (append):
ans.append(word)
return ans