For example if the parenthesis/brackets is matching in the following:
({})
(()){}()
()
and so on but if the parenthesis/brackets is not mat
Problem Statement: Check for balanced parentheses in an expression Or Match for Open Closing Brackets
If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure Solution in C#
public void OpenClosingBracketsMatch()
{
string pattern = "{[(((((}}])";
Dictionary matchLookup = new Dictionary();
matchLookup['{'] = '}';
matchLookup['('] = ')';
matchLookup['['] = ']';
Stack stck = new Stack();
for (int i = 0; i < pattern.Length; i++)
{
char currentChar = pattern[i];
if (matchLookup.ContainsKey(currentChar))
stck.Push(currentChar);
else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
{
char topCharFromStack = stck.Peek();
if (matchLookup[topCharFromStack] != currentChar)
{
Console.WriteLine("NOT Matched");
return;
}
}
}
Console.WriteLine("Matched");
}
For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/