Drill

ProblemsC++ › patterns

Balanced delimiters

easypatternsStacksStringsC++

A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.

balancedDelimiters(text: string) → bool

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

bool balancedDelimiters(std::string text) {
    
}

Worked examples

CallResult
balancedDelimiters(std::string("()"))true
balancedDelimiters(std::string("([])"))true
balancedDelimiters(std::string("(]"))false
balancedDelimiters(std::string("[(])"))false

Hint

Push each opener, and when a closer arrives the top of the stack must be its matching opener.

Reference solution in C++
bool balancedDelimiters(std::string text) {
    std::vector<char> expect;
    for (char ch : text) {
        if (ch == '(') expect.push_back(')');
        else if (ch == '[') expect.push_back(']');
        else if (ch == '{') expect.push_back('}');
        else if (ch == ')' || ch == ']' || ch == '}') {
            if (expect.empty() || expect.back() != ch) return false;
            expect.pop_back();
        }
    }
    return expect.empty();
}

The same problem in another language

More patterns problems in C++