DAY 23
0

# 500. Keyboard Row

## Question

Given an array of strings `words`, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

• the first row consists of the characters `"qwertyuiop"`,
• the second row consists of the characters `"asdfghjkl"`, and
• the third row consists of the characters `"zxcvbnm"`.

## Example

### Example1

``````Input: words = ["Hello","Alaska","Dad","Peace"]
``````

### Example2

``````Input: words = ["omk"]
Output: []
``````

### Example3

``````Input: words = ["adsdf","sfd"]
``````

### Constraints

• `1 <= words.length <= 20`
• `1 <= words[i].length <= 100`
• `words[i]` consists of English letters (both lowercase and uppercase).

## 解題

### Think

• 用一個dictionary存每個字母對應在鍵盤上的那一列，然後一個字一個字去判斷只要其中有一個字跟前一個字的`row`不同就跳出判斷這個字串的迴圈，往下個字串找。
• C再補上，先睡啦。

### Code

#### Python

``````class Solution:
def findWords(self, words: List[str]) -> List[str]:
dict = {'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':3, 'X':3, 'C':3, 'V':3, 'B':3, 'N':3, 'M':3}
ans = []
flag = False

for word in words:
row = 0
for index in range(len(word)):
if len(word) == 1:
flag = True

if row != 0:
if row == dict[word[index].upper()]:
flag = True
continue
else:
flag = False
break
else:
row = dict[word[index].upper()]

if flag:
ans.append(word)

return ans

``````

#### C

``````
``````

• Python

• ## C

30天 Leetcode解題之路30

### 1 則留言

0
soft_soft
iT邦新手 5 級 ‧ 2021-10-08 20:39:01