Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class StackArray {
- private int size;
- private char[] array;
- private int top;
- public StackArray(int s){//конструктор стека
- size = s;
- array = new char[size];
- top = -1;
- }
- public boolean isEmpty(){//проверяем стек на пустоту
- return (top == -1);
- }
- public void push(char a){//добавление элемента в стек
- top++;
- array[top] = a;
- }
- public char pop(){//удаление элемента из стека
- if (top == -1) {
- System.out.println("Stack is empty");
- return '\0';
- }
- else {
- return array[top--];
- }
- }
- public int pick(){//верхушка элемента
- if (top == -1) {
- System.out.println("Stack is empty");
- return 0;
- }
- else {
- return array[top];
- }
- }
- public static boolean checkPair(char el1, char el2){//чекаем пару
- if (el1 == '(' && el2 == ')')
- return true;
- else if (el1 == '{' && el2 == '}')
- return true;
- else if (el1 == '[' && el2 == ']')
- return true;
- else
- return false;
- }
- public static boolean balance(int a, ArrayList<Character> myArray){//самое интересное, проверяем баланс
- StackArray stack = new StackArray(a);
- for (int i = 0; i < a; i++){
- if (myArray.get(i) == '{' || myArray.get(i) == '(' || myArray.get(i) == '['){//если собка открывающаяся
- stack.push(myArray.get(i));
- }
- if (myArray.get(i) == '}' || myArray.get(i) == ')' || myArray.get(i) == ']'){//если скобка закрывающаяся
- if (stack.isEmpty())//если стек пустой, то вернем ложь
- return false;
- else if (!checkPair(stack.pop(), myArray.get(i)))
- return false;
- }
- }
- return true;
- }
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- int n = reader.nextInt();
- System.out.println("Количество элементов: " + n);
- ArrayList<Character> myArray = new ArrayList<>(n);
- for (int i = 0; i < n; i++){
- char el = reader.next().charAt(0);
- myArray.add(i, el);
- System.out.print(myArray.get(i) + " ");
- }
- if (balance(n, myArray))
- System.out.println("Balanced ");
- else
- System.out.println("Not Balanced ");
- }
- }
Add Comment
Please, Sign In to add comment