Untitled
unknown
c_cpp
a year ago
1.2 kB
13
Indexable
#include <iostream> #include <vector> #include <unordered_map> #include <algorithm> std::string solve(const std::string& s, int k) { // Equivalent to Python's collections.Counter std::unordered_map<char, int> char_count; for (char ch : s) { ++char_count[ch]; } // Creating a sorted set of unique characters std::vector<int> orders; for (char ch : s) { orders.push_back(ch); } sort(orders.begin(), orders.end()); orders.erase(unique(orders.begin(), orders.end()), orders.end()); std::string t; for (int i = k - 1; i >= 0; --i) { auto pos = std::find(orders.begin(), orders.end(), s[i]); if (std::distance(orders.begin(), pos) == k - 1) { t += orders.front(); } else { int idx = std::distance(orders.begin(), pos); t += orders[idx + 1]; std::string dummy(i, orders.front()); t += dummy; break } } // Reverse the string before returning std::reverse(t.begin(), t.end()); return t; } int main() { std::string s = "example"; int k = 3; std::string result = solve(s, k); std::cout << "Result: " << result << std::endl; return 0; }
Editor is loading...
Leave a Comment