题目:
给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。
示例:
输入:words = [“Hello”,“Alaska”,“Dad”,“Peace”]
输出:[“Alaska”,“Dad”]
方法:遍历
我们为每一个英文字母标记其对应键盘上的行号,然后检测字符串中所有字符对应的行号是否相同。
我们可以预处理计算出每个字符对应的行号。
遍历字符串时,统一将大写字母转化为小写字母方便计算。
代码:
class Solution:
def findWords(self, words: List[str]) -> List[str]:
ans = []
rowIdx = "12210111011122000010020202"
for word in words:
idx = rowIdx[ord(word[0].lower()) - ord('a')]
if all(rowIdx[ord(ch.lower()) - ord('a')] == idx for ch in word):
ans.append(word)
return ans