Hard csharp

Collections — Stack balanced brackets

Problem

Use Stack<char> to validate bracket string ([]){}.

Hints
  • Push open, pop and match on close

Your practice code

Ready — edit the code above and click Run.

Solution

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        string s = "([]){}";
        var st = new Stack<char>();
        var pairs = new Dictionary<char, char> { [')'] = '(', [']'] = '[', ['}'] = '{' };
        bool ok = true;
        foreach (var ch in s) {
            if ("([{".Contains(ch)) st.Push(ch);
            else if (st.Count == 0 || st.Pop() != pairs[ch]) { ok = false; break; }
        }
        Console.WriteLine(ok && st.Count == 0);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Stack + hash map for brackets—top FAANG question using collections.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details