方法一:
class Solution:
def findWords(self, words: List[str]) -> List[str]:
lst = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
res = []
for word in words: # word = 'hello'
length = len(word)
for s in lst: # s = "qwertyuiop"
count = 0
for i in word.lower(): # i = 'h'
if i in s:
count += 1
else:
break
if length == count:
res.append(word)
return res
方法二:a.issubset(b)
表示求字符串a是否是b的子集。
class Solution:
def findWords(self, words: List[str]) -> List[str]:
# 方法二:求字符串交集
line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
ret = []
for word in words:
w = set(word.lower())
if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
ret.append(word)
return ret
方法三:哈希表
代码链接:https://leetcode.cn/problems/keyboard-row/solution/-by-liupengsay-61iv/
思路:
- 首先将keyboard映射为哈希表,键为字母,值为所在行索引。
- 然后遍历words中每个字母,是否等于第一个字母所在行。
keyboard = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
row = dict()
for i, string in enumerate(keyboard):
for w in string:
row[w] = i
class Solution:
def check(self, word):
group = row[word[0]]
for va in word[1:]:
if row[va] != group:
return False
return True
def findWords(self, words: List[str]) -> List[str]:
return [word for word in words if self.check(word.lower())]