Problem
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.
Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row.
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”.
Algorithm
The simplest algorithm is to directly compare using enumeration, or you can use a dictionary to store queries.
Code
class Solution:def findWords(self, words: List[str]) -> List[str]:row = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]ans = []for word in words:find_letter = [0, 0, 0]for letter in word:if letter >= 'A' and letter <= 'Z':letter = chr(ord(letter) + ord('a') - ord('A'))for i in range(3):for s in row[i]:if s == letter:find_letter[i] = 1breakif find_letter[0] + find_letter[1] + find_letter[2] == 1:ans.append(word)return ans