Mid From PDF Coding C# Coding Interview

Check if a string has balanced brackets?

public bool IsBalanced(string s) {
Stack<char> stack = new Stack<char>();
Dictionary<char, char> pairs = new Dictionary<char, char> {

{')', '('}, {']', '['}, {'}', '{'}

};

foreach (char c in s) {
if ("([{".Contains(c))

stack.Push(c);

else if (")]}".Contains(c)) {

if (stack.Count == 0 || stack.Pop() != pairs[c])
return false;
}
}
return stack.Count == 0;
}

Follow on:

Explanation:

Use a stack to match opening and closing brackets properly.

More from C# Programming Tutorial

All questions for this course
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