Parenthesis Learn programming Visual Basic (VB.net)

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:

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

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