Ejercicio
Paréntesis
Objetivo
Implementar una función para comprobar si una secuencia de paréntesis abierto y cerrado está equilibrada, es decir, si cada paréntesis abierto corresponde a uno cerrado y además están bien anidados.
Por ejemplo:
(()()(())) OK
(((() ERROR
Código de Ejemplo
using System;
using System.Collections.Generic;
class Program
{
static bool IsBalanced(string parentheses)
{
Stack stack = new Stack();
foreach (char ch in parentheses)
{
if (ch == '(')
{
stack.Push(ch);
}
else if (ch == ')')
{
if (stack.Count == 0)
{
return false;
}
stack.Pop();
}
}
return stack.Count == 0;
}
static void Main(string[] args)
{
string test1 = "(()()(()))";
string test2 = "(((()";
Console.WriteLine($"Is the sequence '{test1}' balanced? {IsBalanced(test1)}");
Console.WriteLine($"Is the sequence '{test2}' balanced? {IsBalanced(test2)}");
}
}