Embercode
✕
Stacks and QueuesQuick quiz

Two-stack calculators and string decoding

8 questions. Covers Decode nested strings and simplify paths.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <cctype> #include <iostream> #include <stack> #include <string> std::string decode(const std::string& s) { struct Frame { int repeat; std::string prefix; }; std::stack<Frame> frames; std::string current; int number = 0; for (char c : s) { if (std::isdigit(static_cast<unsigned char>(c))) { number = number * 10 + (c - '0'); } else if (c == '[') { frames.push({number, current}); number = 0; current.clear(); } else if (c == ']') { Frame f = frames.top(); frames.pop(); std::string block; for (int i = 0; i < f.repeat; ++i) { block += current; } current = f.prefix + block; } else { current += c; } } return current; } int main() { std::cout << decode("3[x2[y]]z") << '\n'; } ``
  2. 2. In the decoder, what happens when a ] is read?
  3. 3. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <string> #include <string_view> #include <vector> std::string simplify_path(std::string_view path) { std::vector<std::string> stack; std::string part; for (std::size_t i = 0; i <= path.size(); ++i) { char c = i < path.size() ? path[i] : '/'; if (c != '/') { part += c; continue; } if (part.empty() || part == ".") { // nothing to do } else if (part == "..") { if (!stack.empty()) { stack.pop_back(); } } else { stack.push_back(part); } part.clear(); } std::string result; for (const auto& name : stack) { result += "/" + name; } return result.empty() ? "/" : result; } int main() { std::cout << simplify_path("/x/y/../../../z/./") << '\n'; } ``
  4. 4. What does this program print? ``cpp #include <iostream> #include <stack> #include <string> int precedence(char op) { return (op == '*' || op == '/') ? 2 : 1; } void apply(std::stack<long long>& values, char op) { long long right = values.top(); values.pop(); long long left = values.top(); values.pop(); switch (op) { case '+': values.push(left + right); break; case '-': values.push(left - right); break; case '*': values.push(left * right); break; default: values.push(left / right); break; } } long long evaluate(const std::string& text) { std::stack<long long> values; std::stack<char> ops; for (char c : text) { if (c == ' ') continue; if (c >= '0' && c <= '9') { values.push(c - '0'); } else { while (!ops.empty() && precedence(ops.top()) >= precedence(c)) { apply(values, ops.top()); ops.pop(); } ops.push(c); } } while (!ops.empty()) { apply(values, ops.top()); ops.pop(); } return values.top(); } int main() { std::cout << evaluate("9 - 6 / 2 * 4 - 1") << '\n'; } ``
  5. 5. A student reorders the ] branch of decode like this: ``cpp } else if (c == ']') { Frame f = frames.top(); if (frames.empty()) { throw std::invalid_argument("unmatched ']'"); } frames.pop(); // repeat current and join f.prefix, as before } `` What is wrong with it?

5 question(s) left on this page.