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;
}
};