Last Updated:

How Stack in Java - With Examples

Our string will not necessarily contain Java code, but the use of parentheses in the program should still be consistent with Java rules. Today we will work with three types of brackets:

  • {} - Curly
  • [] -kvadratnimi
  • () -round

Let's form the rules for using these elements:

  • Each opening bracket must have a closing bracket
  • brackets that are near the end of the line must be closed earlier

A bit confusing, isn't it? Let's look at examples:

  • [c] [/c]

    d – proper use

  • a{b

    [c] [/c]

    d}e – proper use

  • a {b (c] d} e is misuse, ] does not correspond (
  • a [b {c} d] e} - Misuse, there is no pair in the closing bracket }
  • a {b (c) is an incorrect use, there is no pair in the opening bracket {

Aglorrhythm of work

The parentheses search program reads the characters of the string by character and enters the found opening brackets into the stack. When a closing parenthesis appears in the input, the program retrieves the top element from the stack and compares their types. If the bracket types are different, an error occurs. Also, our program provides for the output of an error if there is no pair for some brackets.

Consider the stack state when parsing the string a {b (c [d] e) f}

During the operation of the program, each opening parenthesis is entered into the stack. Each closing bracket is compared to the top of the stack and if they form a pair, then everything is fine. We put only parentheses in the stack, and ignore the rest of the characters. Thus, a pair of brackets opened last will be closed first. A perfect illustration of the principle of LIFO (first in, first out).

This concludes our theoretical part.

Example of using the Stack in Java

First, let's implement the stack class. An explanation of it was provided in the previous article, so we will not repeat ourselves:

The next step is to implement the class that will be responsible for solving our problem:

Let's create the fields:

  • input — accepts the string to be validated
  • lengthInput — includes the size of the entered string
  • stack - An object of the Stack class

 

Remember! The constructor is designed to initialize data, so declare variables before the constructor. Let's create a method that will contain an algorithm for checking whether the parentheses are entered correctly. Let's start to go through our line element by element and if we meet the opening bracket, we put it in the stack.makeCheck

When the algorithm finds a closing parenthesis, it is compared with the last bracket added to the stack and the corresponding response of the validation algorithm (or an error message, or the continuation of the program).

And finally the class:main

The result of the program:

An example of working with a stack in java is ready.