500. keyboard row

Description

Difficulty: Easy

Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard.

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.

给一组词(字母组成),返回一子集,其中单词可仅用键盘上某一行打出。

Solution

先创建三个字符串,分别包含键盘上三行的字母(大小写),然后遍历每个单词后续字母是否与第一个字母在同一行;注意发现不同时跳过当前单词节省时间。

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
30
31
class (object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
row1 = 'qwertyuiopQWERTYUIOP'
row2 = 'asdfghjklASDFGHJKL'
row3 = 'zxcvbnmZXCVBNM'
rslt = []
if words == []:
return []
for i in words:
lead = []
if i[0] in row1:
lead = row1
elif i[0] in row2:
lead = row2
elif i[0] in row3:
lead = row3
diff = 0
for j in i:
if j not in lead:
diff = 1
break
if diff == 0:
rslt.append(i)
return rslt