Algorithms with C# · Lesson 5

Stacks and nesting

Use last-in-first-out order to match nested delimiters.

How it works

A stack is useful when the most recently opened item must be closed first. Each opening bracket is pushed, and a closing bracket must match the character at the top. A mismatched closer fails immediately, while leftover openers at the end also make the input invalid. This lesson checks only parentheses and square brackets and deliberately ignores ordinary text. It is not a C# parser: brackets inside quoted strings or comments would require lexical rules.

State the input language before extending a small delimiter checker so its limitations remain visible and the implementation does not acquire accidental claims.

Test empty text, a lone closer, and leftover openers. Explain why a string containing quoted bracket characters requires a richer input model than this checker understands.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

Console.WriteLine(Balanced("([])"));
Console.WriteLine(Balanced("([)]"));
bool Balanced(string text)
{
    var stack = new Stack<char>();
    foreach (var ch in text)
    {
        if (ch is '(' or '[') stack.Push(ch);
        else if (ch is ')' or ']')
        {
            if (stack.Count == 0) return false;
            var open = stack.Pop();
            if ((ch == ')' && open != '(') || (ch == ']' && open != '[')) return false;
        }
    }
    return stack.Count == 0;
}

Expected output

True
False
Try this
The last opening delimiter must be the first one closed.