当前位置: 面试刷题>> 最高频的k个单词 (经典算法题500道)


题目描述

给定一个字符串s,其中包含了由空格分隔的单词,以及一个整数k。请找出并返回字符串s中出现频率最高的k个单词。返回的单词列表需要按频率从高到低排序,如果频率相同,则按字典序从低到高排序。

注意

  1. 单词只由小写字母组成。
  2. 你可以假设k总是有效的,即k小于等于单词列表中单词的总数。

示例

输入:

  • 字符串s: "the day is sunny the the the windy day is beautiful"
  • 整数k: 4

输出: ["the", "day", "is", "sunny"]

解释: "the" 出现了4次,"day" 和 "is" 各出现了2次,"sunny" 出现了1次。按频率排序后,"windy" 和 "beautiful" 不在结果中,因为它们只出现了1次。

PHP 示例代码

function topKFrequent($s, $k) {
    $words = preg_split('/\s+/', strtolower($s)); // 使用正则分割单词并转为小写
    $freq = array_count_values($words); // 统计每个单词的频率
    arsort($freq); // 按频率降序排序,保持索引关联

    $result = [];
    foreach ($freq as $word => $count) {
        $result[] = $word;
        if (count($result) == $k) {
            break;
        }
    }

    // 如果需要按字典序排序相同频率的单词
    uksort($result, function($a, $b) use ($freq) {
        if ($freq[$a] == $freq[$b]) {
            return strcmp($a, $b);
        }
        return 0;
    });

    return $result;
}

// 示例
$s = "the day is sunny the the the windy day is beautiful";
$k = 4;
print_r(topKFrequent($s, $k));

注意:由于PHP的arsort保持索引关联,直接对结果排序可能不会按字典序处理相同频率的单词。上述代码在最后使用uksort进行了补充排序,但这种方式可能不是最高效的。对于实际应用,可能需要先按频率分组,再在每个分组内按字典序排序。

Python 示例代码

from collections import Counter

def topKFrequent(s, k):
    words = s.lower().split()
    freq = Counter(words)
    sorted_words = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
    return [word for word, _ in sorted_words[:k]]

# 示例
s = "the day is sunny the the the windy day is beautiful"
k = 4
print(topKFrequent(s, k))

JavaScript 示例代码

function topKFrequent(s, k) {
    const words = s.toLowerCase().split(/\s+/);
    const freq = {};
    for (const word of words) {
        if (freq[word]) {
            freq[word]++;
        } else {
            freq[word] = 1;
        }
    }

    const sortedWords = Object.entries(freq).sort((a, b) => {
        if (a[1] === b[1]) {
            return a[0].localeCompare(b[0]);
        }
        return b[1] - a[1];
    });

    return sortedWords.slice(0, k).map(word => word[0]);
}

// 示例
const s = "the day is sunny the the the windy day is beautiful";
const k = 4;
console.log(topKFrequent(s, k));

码小课网站中有更多相关内容分享给大家学习,包括但不限于算法解析、面试技巧、编程实践等,欢迎访问学习!

推荐面试题