题目来源
题目描述
题目解析
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
std::vector<std::string> split(std::string str, char ch){
str += ch;
int i = 0;
std::vector<std::string> ans;
for (int j = 0; j < str.size(); ++j) {
if(str[j] == ch){
ans.push_back(str.substr(i, j - i));
i = j + 1;
}
}
return ans;
}
int main(int argc, char **argv)
{
std::vector<std::vector<int>> sprintBuilder;
std::string str = "20-21,15,18,30,5-10";
int rIdx = 15;
// std::cin >> str;
// std::cin >> rIdx;
auto tmp = split(str, ',');
for(std::string &it : tmp){
auto t = split(it, '-');
if(t.size() == 1){
int id = stoi(it);
if(id == rIdx){
continue;
}
sprintBuilder.push_back({id, id});
}else{
int first = stoi(t[0]);
int second = stoi(t[1]);
if(first == rIdx){
sprintBuilder.push_back({first + 1, second});
}else if(second == rIdx){
sprintBuilder.push_back({first, second - 1});
}else if(rIdx > first && rIdx < second){
sprintBuilder.push_back({first, rIdx - 1});
sprintBuilder.push_back({rIdx + 1, second});
}else{
sprintBuilder.push_back({first, second});
}
}
}
std::sort(sprintBuilder.begin(), sprintBuilder.end(), [](std::vector<int> &a, std::vector<int> &b){
return a[0] < b[0];
});
std::string ans;
for (auto & i : sprintBuilder) {
int first = i[0];
int second = i[1];
if(first == second){
ans += ans.empty() ? std::to_string(first) : "," + std::to_string(first);
}else{
ans += ans.empty() ? std::to_string(first) + "-" + std::to_string(second) : "," + std::to_string(first) + "-" + std::to_string(second) ;
}
}
std::cout << ans <<"\n";
}