iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

30天 Leetcode解題之路系列 第 23

Day 23 - Keyboard Row

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


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"]
Output: ["Alaska","Dad"]

Example2

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

Example3

Input: words = ["adsdf","sfd"]
Output: ["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


Result

  • Python

  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 22 - Shortest Distance to a Character
下一篇
Day 24 - Single Number
系列文
30天 Leetcode解題之路30

1 則留言

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

數數字囉5

我要留言

立即登入留言