大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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:
"qwertyuiop","asdfghjkl", and"zxcvbnm".
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Input: words = ["omk"]
Output: []
Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]
1 <= words.length <= 20
1 <= words[i].length <= 100
words[i] consists of English letters (both lowercase and uppercase).首先先簡單的翻譯一下題目
給一組陣列的字串,要判斷其中每個字使用到的字母是不是都在鍵盤上的同一列。
作法大致上是這樣
row不同就跳出判斷這個字串的迴圈,往下個字串找。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
Python
大家明天見![]()