每日一题 2023.10.11

博客围绕LeetCode的2512题展开,涉及对字符串的处理,需读取长句中的每个单词。解题思路结合简单字符串处理、用unordered_map处理映射关系、用priority_queue方便排序,属于信息技术领域的算法与数据结构问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2512. 奖励最顶尖的 K 名学生 - 力扣(LeetCode)

get:

        对字符串的处理:读取一长段句子的每一个word

//vector<string> report;

for(int i=0;i<report.size();i++){
    stringstream ss;
    string s;
    ss<<report[i];//读入
    while(ss>>s){//把ss的逐个输出给s
        cout<<s<<endl;//这里为对每个s进行操作
    }
}

例:

#include<cstring>
#include<iostream>
#include<sstream>
using namespace std;
int main(){
 
    vector<string> report={"k-on!","I went to the wood","suck out all the marrow of life"};
    for(int i=0;i<report.size();i++){
        stringstream ss;
        ss<<report[i];
        string w;
        while(ss>>w){
            cout<<w<<" ";
        }
        cout<<endl;
    }
}

输出结果:

题目思路:简单的字符串处理问题+unordered_map(处理映射关系 从string->int)+priority_queue(方便排序)

AC code:

class Solution {
public:
    typedef pair<int,int>PII;
    vector<int> topStudents(vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) {

        unordered_map<string,int> words;
        for(auto word:positive_feedback){
            words[word]=3;
        }
        for(auto word:negative_feedback){
            words[word]=-1;
        }
        priority_queue<PII,vector<PII>,greater<PII> >heap;
        for(int i=0;i<report.size();i++){
            stringstream ss;
            string w;
            int score=0;
            ss<<report[i];
            while(ss>>w){
                if(words.count(w)){
                    score+=words[w];
                }
            }
            heap.push({-score,student_id[i]});
        }
        vector<int> res;

        while(k--){
            auto t=heap.top();
            heap.pop();
            res.push_back(t.second);
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值