Decoded String at Index LeetCode solution in C++
1class Solution {2public:3string decodeAtIndex(string s, int k) {4k--;5struct op {6string s;7size_t mult;8size_t total;9};10vector<op> v;11size_t total = 0;12for (auto c : s) {13if (isalpha(c)) {14if (v.empty() || v.back().mult > 1) v.push_back({"", 1, total});15v.back().s += c;16v.back().total = ++total;17} else {18size_t m = c - '0';19v.back().mult *= m;20v.back().total = total *= m;21}22if (total > k) break;23}24while (!v.empty()) {25auto [s, mult, total] = v.back();26v.pop_back();27size_t part = total / mult;28k %= part;29if (size_t i = k - part + s.size(); i < s.size()) return {s[i]};30}31return "#";32}33};