Parenthesis Learn programming Visual Basic (VB.net)

Lesson:

Dynamic Memory Management


Exercise:

Parenthesis 6


Objetive:

Implement a function to check if a sequence of opened and closed parenthesis is balanced, in other words, if each opened parenthesis corresponds to one closed and they are also well nested.

For example:

(()()(())) OK
(((() ERROR


Code:

Imports System
Imports System.Collections
Namespace Expression
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim expresion As String = "()()()()()()"
            Dim expresionMal As Boolean = False
            Dim pila As Stack = New Stack()

            For i As Integer = 0 To expresion.Length - 1

                If expresion(i) = "("c Then
                    pila.Push(expresion(i))
                ElseIf expresion(i) = ")"c Then

                    If pila.Count > 0 Then
                        pila.Pop()
                    Else
                        expresionMal = True
                    End If
                End If
            Next

            If expresionMal Then
                Console.WriteLine("ERROR")
            Else
                Console.WriteLine("OK")
            End If

            Console.ReadLine()
        End Sub
    End Class
End Namespace