Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stack_parantheses_check;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.NoSuchElementException;
- interface Stack<E> {
- // Elementi na stekot se objekti od proizvolen tip.
- // Metodi za pristap:
- public boolean isEmpty();
- // Vrakja true ako i samo ako stekot e prazen.
- public E peek();
- // Go vrakja elementot na vrvot od stekot.
- // Metodi za transformacija:
- public void clear();
- // Go prazni stekot.
- public void push(E x);
- // Go dodava x na vrvot na stekot.
- public E pop();
- // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
- }
- class ArrayStack<E> implements Stack<E> {
- private E[] elems;
- private int depth;
- @SuppressWarnings("unchecked")
- public ArrayStack(int maxDepth) {
- // Konstrukcija na nov, prazen stek.
- elems = (E[]) new Object[maxDepth];
- depth = 0;
- }
- public boolean isEmpty() {
- // Vrakja true ako i samo ako stekot e prazen.
- return (depth == 0);
- }
- public E peek() {
- // Go vrakja elementot na vrvot od stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- return elems[depth - 1];
- }
- public void clear() {
- // Go prazni stekot.
- for (int i = 0; i < depth; i++)
- elems[i] = null;
- depth = 0;
- }
- public void push(E x) {
- // Go dodava x na vrvot na stekot.
- elems[depth++] = x;
- }
- public E pop() {
- // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- E topmost = elems[--depth];
- elems[depth] = null;
- return topmost;
- }
- }
- public class Parantheses {
- public static boolean isValid(String sequence) {
- ArrayStack<Character> stack = new ArrayStack<Character>(50);
- for (int i = 0; i < sequence.length(); i++) {
- if (sequence.charAt(i) == '{') {
- stack.push(sequence.charAt(i));
- } else if (sequence.charAt(i) == '[') {
- stack.push(sequence.charAt(i));
- } else if (sequence.charAt(i) == '(') {
- stack.push(sequence.charAt(i));
- } else if (sequence.charAt(i) == ')') {
- if (stack.isEmpty()) {
- return false;
- }
- if (stack.pop() != '(') {
- return false;
- }
- } else if (sequence.charAt(i) == ']') {
- if (stack.isEmpty()) {
- return false;
- }
- if (stack.pop() != '[') {
- return false;
- }
- } else if (sequence.charAt(i) == '}') {
- if (stack.isEmpty()) {
- return false;
- }
- if (stack.pop() != '{') {
- return false;
- }
- }
- }
- return stack.isEmpty();
- }
- public static void main(String[] args) throws IOException {
- BufferedReader stdin = new BufferedReader(new InputStreamReader(
- System.in));
- String sequence = stdin.readLine().trim();
- System.out.println(isValid(sequence));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement