...

/

Solution Review: Check Balanced Parentheses Using Stack

Solution Review: Check Balanced Parentheses Using Stack

This review provides a detailed analysis to help you solve the "Check Balanced Parentheses Using Stack" challenge.

We'll cover the following...

Solution: A stack of characters

Press + to interact
namespace chapter_4
{
class Challenge_8
{
static bool isBalanced(string exp)
{
//Iterate through the string exp.
//For each opening parentheses, push it into stack
//For every closing parentheses check for its opening parentheses in stack
//If you can't find the opening parentheses for any closing one then return false.
//and after complete traversal of string exp, if there's any opening parentheses left
//in stack then also return false.
//At the end return true if you haven't encountered any of the above false conditions.
Stack<char> stack = new Stack<char> ();
char character;
for (int i = 0; i < exp.Length; i++)
{
character = exp[i];
if (character == '}' || character == ')' || character == ']')
{
if (stack.Count == 0)
return false;
if ((character == '}' && stack.Pop() != '{') || (character == ')' && stack.Pop() != '(') || (character == ']' && stack.Pop() != '['))
return false;
}
else
stack.Push(character);
}
if (stack.Count != 0)
return false;
return true;
}
static void Main(string[] args)
{
Console.WriteLine(isBalanced("{[()]}"));
Console.WriteLine(isBalanced("[{(}]"));
return ;
}
}
}

This is a simple algorithm. Iterate over the string one character at a time. Whenever you find a closing parenthesis, you can deduce that the ...