819. Most Common Word
顺带实验了几种不同的去标点方法,发现的确是translate显著地快,虽然代码有点不直观。
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# 创建个 translate table, 所有 punctutaion 都替换为空格
remove_punct_map = dict.fromkeys(map(ord, string.punctuation), ' ')
freq = Counter([x for x in paragraph.translate(remove_punct_map).lower().split(' ')])
rank = sorted(freq.items(), key = lambda item:item[1], reverse=True)
for w in rank:
if w[0] not in banned and w[0].isalpha():
return w[0]
Last updated
Was this helpful?