Objectivo
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
Ejemplo Ejercicio C#
Mostrar Código C#
// Importing necessary namespace for handling collections
using System; // Basic namespace for console input/output and fundamental operations
using System.Collections.Generic; // For using the Stack class
class Program
{
// Function to check if a sequence of parentheses is balanced
static bool IsBalanced(string parentheses)
{
// Create a stack to hold the open parentheses
Stack stack = new Stack(); // Stack will help to track unmatched open parentheses
// Iterate through each character in the input string
foreach (char ch in parentheses) // For each character in the string
{
// If the character is an opening parenthesis, push it onto the stack
if (ch == '(') // If the character is an open parenthesis
{
stack.Push(ch); // Add the open parenthesis to the stack
}
// If the character is a closing parenthesis, check if there's a matching open parenthesis
else if (ch == ')') // If the character is a closing parenthesis
{
// If the stack is empty, it means no matching open parenthesis, return false
if (stack.Count == 0) // If there are no open parentheses to match with
{
return false; // It means the parentheses are not balanced
}
stack.Pop(); // Remove the top item from the stack (matching the open parenthesis)
}
}
// If the stack is empty, all open parentheses had matching closing parentheses
return stack.Count == 0; // If the stack is empty, the parentheses are balanced
}
// Main program method to test the IsBalanced function
static void Main(string[] args)
{
// Test the IsBalanced function with valid and invalid examples
string test1 = "(()()(()))"; // A valid sequence of parentheses
string test2 = "(((()"; // An invalid sequence of parentheses
// Display the results of the balance check
Console.WriteLine($"Is the sequence '{test1}' balanced? {IsBalanced(test1)}"); // Expecting true
Console.WriteLine($"Is the sequence '{test2}' balanced? {IsBalanced(test2)}"); // Expecting false
}
}
Salida
Is the sequence '(()()(()))' balanced? True
Is the sequence '(((()' balanced? False
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp