[LeetCode] Challenge log 500

500. Keyboard Row

Use dict to map charaters to row numbers.


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.

Soulution:
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
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
whichRow = {}
res = []
rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
for i, row in enumerate(rows):
for char in row:
whichRow[char] = i
for word in words:
if word == "":
res.append(word)
continue
wordLow = word.lower()
flag = True
row = whichRow[wordLow[0]]
for char in wordLow:
if whichRow[char] != row:
flag = False
break
if flag: res.append(word)
return res
0%