有一说一,还是别人写的代码比较妙:
class Solution:
def findWords(self, words):
ans = []
rowIdx = "12210111011122000010020202"
for word in words:
idx = rowIdx[ord(word[0].lower()) - ord('a')]
print(idx)
if all(rowIdx[ord(ch.lower()) - ord('a')] == idx for ch in word):
ans.append(word)
return ans
但我后面觉得这个有点费时,所以改进了一下:
for word in words:
idx = rowIdx[ord(word[0].lower()) - ord('a')]
for ch in word:
if rowIdx[ord(ch.lower()) - ord('a')] != idx:
exit_flag = True
break
if exit_flag:
exit_flag = False
continue
ans.append(word)
一旦发现有不同行的就立马结束循环,这样应该省时一些



