Parenthesis Learn programming C#

Lesson:

Dynamic Memory Management


Exercise:

Parenthesis


Objetive:

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


Code:

using System;
using System.Collections;
namespace Expression
{
    class Program
    {
        static void Main(string[] args)
        {
            string expresion = "()()()()()()";
            bool expresionMal = false;

            Stack pila = new Stack();

            for (int i = 0; i < expresion.Length; i++)
            {
                if (expresion[i] == '(')
                    pila.Push(expresion[i]);
                else if (expresion[i] == ')')
                    if (pila.Count > 0)
                        pila.Pop();
                    else
                        expresionMal = true;
            }

            if (expresionMal)
                Console.WriteLine("ERROR");
            else
                Console.WriteLine("OK");

            Console.ReadLine();
        }
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.