NC97 字符串出现次数的TopK问题

题目描述:

给定一个字符串数组,再给定整数k,请返回出现次数前k名的字符串和对应的次数。
返回的答案应该按字符串出现频率由高到低排序。如果不同的字符串有相同出现频率,按字典序排序。
对于两个字符串,大小关系取决于两个字符串从左到右第一个不同字符的 ASCII 值的大小关系。
比如"ah1x"小于"ahb",“231”<”32“
字符仅包含数字和字母

解题分析:

使用哈希表map统计各个字符串出现的次数,然后按要求排序即可。

class Solution {
    
    
public:
    /**
     * return topK string
     * @param strings string字符串vector strings
     * @param k int整型 the k
     * @return string字符串vector<vector<>>
     */
    static bool sortKey(pair<string,int> elem1, pair<string,int> elem2){
    
    
        if(elem1.second==elem2.second)
            return elem1.first<elem2.first;
        return elem1.second>elem2.second;
    }
    vector<vector<string> > topKstrings(vector<string>& strings, int k) {
    
    
        // write code here
        map<string, int> stringsTimesMap;
        for(auto string:strings){
    
    
            stringsTimesMap[string]++;
        }
        vector<pair<string,int>> stringsTimesVec;
        for(auto keyValue:stringsTimesMap){
    
    
            stringsTimesVec.push_back(keyValue);
        }
        sort(stringsTimesVec.begin(), 
             stringsTimesVec.end(),
            sortKey);
        vector<vector<string>> topKstrs;
        for(int i=0; i<k; i++){
    
    
            topKstrs.push_back({
    
    stringsTimesVec[i].first, to_string(stringsTimesVec[i].second)});
        }
        return topKstrs;
    }
};

Guess you like

Origin blog.csdn.net/MaopengLee/article/details/118853235