500. Keyboard Row

Easy (Dễ) Python 🔗 Xem trên LeetCode

📋 Đề Bài

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 1:

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

Example 2:

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

Example 3:

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). 

💻 Lời Giải

Python 0500-keyboard-row.py
class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        row = {
            0: "qwertyuiop",
            1: "asdfghjkl",
            2: "zxcvbnm"
        }
        
        flag = -1
        answ = []
        
        for word in words:
            if word[0].lower() in row[0]:
                flag = 0
            elif word[0].lower() in row[1]:
                flag = 1
            else:
                flag = 2
                
            check = True
            
            for char in word:
                if char.lower() not in row[flag]:
                    check = False
                    break
            
            if check:
                answ.append(word)
                
        return answ