(SPOJ) 11014 - Expressões - Solução

import java.io.*;
import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main processando = new Main();
        processando.processa();
       
        System.exit(0);
    }
   
    static int leitor(BufferedReader br) throws NumberFormatException, IOException {
        int n;
        int resp = 0;

        while (true) {
            n = br.read();
            if (n >= '0' && n <= '9')
                break;
        }
        while (true) {
            resp = resp*10 + n-'0';
            n = br.read();
            if (n < '0' || n > '9')
                break;
        }

        return resp;
    }
   
    void processa() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int contador = 0;
        int numCasos = leitor(br);
        while (contador < numCasos) {           
            contador++;
           
            String linha = br.readLine();
           
            Stack<Character> pilha = new Stack<Character>();
           
            char ultimo;
            boolean naoDefinido = false;
            int tamLinha = linha.length();
            if (tamLinha%2 != 0) {
                naoDefinido = true;
            }
            else {
                for (int i = 0; i < tamLinha; i++) {
                    char atual = linha.charAt(i);
                    if (atual == '[' || atual == '(' || atual == '{') {
                        pilha.push(atual);
                    }
                    else {
                        if (pilha.empty()) {
                            naoDefinido = true;
                            break;
                        }
                        ultimo = pilha.pop();
                        if (atual == ']' && ultimo != '[') {
                            naoDefinido = true;
                        }
                        else if (atual == '}' && ultimo != '{') {
                            naoDefinido = true;
                        }
                        else if (atual == ')' && ultimo != '(') {
                            naoDefinido = true;
                        }
                    }
                    if (naoDefinido) {
                       break;
                    }
                }
            }
           
            if (naoDefinido) {
                System.out.println("N");
            }
            else {
                System.out.println("S");
            }
        } 
       
        return;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução