场景:
你有一组文章,每篇文章都有一些标签。
需求是:
-
通过文章ID快速查找它的标签(用Map实现)。
-
通过标签快速找到所有包含该标签的文章ID(用Map实现,反向索引)。
-
还能快速去重标签(用Set实现)。
-
支持添加新文章及标签,删除标签,查询功能。
class ArticleTagManager {
constructor() {
// 文章ID -> 标签Set
this.articleTags = new Map();
// 标签 -> 文章ID Set(反向索引)
this.tagArticles = new Map();
}
// 添加文章及其标签
addArticle(articleId, tags) {
if (this.articleTags.has(articleId)) {
console.warn(`文章 ${articleId} 已存在,使用 updateTags 更新标签`);
return;
}
const tagSet = new Set(tags);
this.articleTags.set(articleId, tagSet);
// 更新反向索引
for (const tag of tagSet) {
if (!this.tagArticles.has(tag)) {
this.tagArtic