A bracket is considered to be any one of the following characters: (, ), {?, }?, [, or ] and matching or pair of brackets are () or {?}? or [].
You are required to check if the expression is balanced, i.e. closing brackets and opening brackets match up well. Write a function that takes a string input containing a sequence of brackets, and returns a boolean indicating whether those brackets are balanced. You can assume the input string only contains valid bracket characters.
Examples:
Input: "{?{?[[(())]]}?}?"
Output: true
Input: "({?])"
Output: false
Input: "{?[]()[()]}?"
Output: true
Input: "[(])"
Output: false
Purushottam RathorePosted Jun 9, 2022, 4:04 PM
using System;
stck = new Stack();
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter string i.e. [[(({}))]]?");
char[] exp = Console.ReadLine().ToCharArray();
if (CheckBrackets(exp))
Console.WriteLine("Balanced ");
else
Console.WriteLine("Not Balanced ");
Console.ReadKey();
}
// Return true if expression has balanced Brackets
static Boolean CheckBrackets(char[] exp)
{
// Declare an empty character stack */
Stack
// Traverse the given expression to check matching brackets
for (int i = 0; i < exp.Length; i++)
{
//If the exp[i] is a starting bracket then push it
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
stck.Push(exp[i]);
//If exp[i] is an ending bracket then pop from stack and check if the popped bracket is a matching pair
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
// If we see an ending bracket without a pair then return false
if (stck.Count == 0)
{
return false;
}
// Pop the top element from stack, if it is not a pair brackets of character then there is a mismatch. This happens for expressions like {(})
else if (!isPairMatching(stck.Pop(), exp[i]))
{
return false;
}
}
}
// If there is something left in expression then there is a starting bracket without a closing bracket
if (stck.Count == 0)
return true; // balanced
else
return false; // not balanced
}
// Returns true if character1 and character2 are matching left and right brackets */
static Boolean isPairMatching(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return true;
else if (character1 == '{' && character2 == '}')
return true;
else if (character1 == '[' && character2 == ']')
return true;
else
return false;
}
}
}