Balanced Parentheses with a Stack
csharpC# and .NETinterview-prepintermediate
Check that brackets are properly closed and nested using Stack of char: push openers, pop and match on closers.
Console.WriteLine(IsBalanced("{[()]}")); // True
Console.WriteLine(IsBalanced("{[(])}")); // False
Console.WriteLine(IsBalanced("((")); // False
Console.WriteLine(IsBalanced("")); // True
// O(n) time. A closer must match the most recent opener, which is exactly what a stack gives you.
static bool IsBalanced(string text)
{
var stack = new Stack<char>();
foreach (char c in text)
{
if (c is '(' or '[' or '{')
{
stack.Push(c);
}
else if (c is ')' or ']' or '}')
{
if (stack.Count == 0) return false;
char open = stack.Pop();
bool matches = (c == ')' && open == '(') || (c == ']' && open == '[') || (c == '}' && open == '{');
if (!matches) return false;
}
}
return stack.Count == 0;
}