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

public bool BalancedDelimiters(string text) {
    
}

Worked examples

CallResult
BalancedDelimiters("()")true
BalancedDelimiters("([])")true
BalancedDelimiters("(]")false
BalancedDelimiters("[(])")false

Hint

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

Reference solution in C#
public bool BalancedDelimiters(string text) {
    var expect = new Stack<char>();
    foreach (char ch in text) {
        if (ch == '(') expect.Push(')');
        else if (ch == '[') expect.Push(']');
        else if (ch == '{') expect.Push('}');
        else if (ch == ')' || ch == ']' || ch == '}') {
            if (expect.Count == 0 || expect.Pop() != ch) return false;
        }
    }
    return expect.Count == 0;
}

The same problem in another language

More patterns problems in C#