Objective
Implement a function to check if a sequence of open and closed parentheses is balanced. In other words, check if each open parenthesis corresponds to a closing one and they are correctly nested.
For example:
"(()()(()))" is OK
"(((()" is an ERROR
Write Your C# Exercise
C# Exercise Example
// 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
}
}