查找英文文章中出现频率最高的单词
题目:给定一段英文文章,返回出现次数最多的单词(忽略大小写、标点)。
function findMostWord(article) {
// 把非字母字符替换为空格,统一转为小写后切词
const words = article
.toLowerCase()
.replace(/[^a-z0-9\s]/g, " ")
.split(/\s+/)
.filter(Boolean);
const map = new Map();
let max = 0;
for (const w of words) {
const count = (map.get(w) || 0) + 1;
map.set(w, count);
if (count > max) max = count;
}
// 返回所有出现次数等于最大值的单词(可能不止一个)
const result = [];
for (const [w, c] of map) {
if (c === max) result.push(w);
}
return { word: result, count: max };
}
const article = "JavaScript is a lightweight, interpreted programming language. JavaScript is also a scripting language.";
findMostWord(article);
// { word: ["javascript"], count: 2 }
补充
补充:原笔记里只留了空函数,这里给出基于 Map 计数的实现,复杂度 O(n)。如果文章很长,可以边遍历边维护最大计数,少一次遍历。



