思路1:暴力法
判断后续字符是否和首字母字符在同一个集合
class Solution:
def findWords(self, words: List[str]) -> List[str]:
set1 = set('qwertyuiop') # 注意不能写成{'qwertyuiop'}
set2 = set('asdfghjkl')
set3 = set('zxcvbnm')
if not words:return []
ans = []
for word in words:
flag =True # 确定当前单词是否在同一行
if word[0].lower() in set1: # 注意全部转换成小写比较
curset = set1 # 记录首字母所在集合
elif word[0].lower() in set2:
curset = set2
else:
curset = set3
for i in range(1,len(word)): # 检查后续字母是否在首字母所在集合,不在则退出
if not word[i].lower() in curset:
flag=False
break
if flag:
ans.append(word)
return ans
思路2:
直接把每个单词转换成集合,判断是否是上面三个集合的子集
setx.issubset(set1)
判断setx是否是set1的子集,等价于setx<=set1
class Solution:
def findWords(self, words: List[str]) -> List[str]:
set1 = set('qwertyuiop')
set2 = set('asdfghjkl')
set3 = set('zxcvbnm')
ans = []
for i in words:
x = i.lower()
setx = set(x) # 直接把每个单词转换成集合,判断是否是上面三个集合的子集
if setx.issubset(set1) or setx.issubset(set2) or setx.issubset(set3):
ans.append(i)
return ans