First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Wednesday, July 16, 2014

Parentheses Balance.

Author : Jisan
Programming language : Java
Difficulty : Advance
Status : Accepted
Problem number : UVA-673
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=614

Help: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html and http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Uva_673Demo {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(bf.readLine());
        while (N-- != 0) {
            boolean jisan = false;
            char[] cs = bf.readLine().toCharArray();
            Stack<Character> st = new Stack<Character>();
            for (char c : cs) {
                if (c == '[' || c == '(') {
                    st.push(c);
                } else {
                    if (c == ']') {
                        if (st.isEmpty() || st.peek() == '(') {
                        jisan = true;
                        }
                    } else if (c == ')') {
                        if (st.isEmpty() || st.peek() == '['){
                        jisan = true;
                        }
                    }
                    if (!st.isEmpty()){
                    st.pop();
                    }
                }
            }
            if (!st.isEmpty())
            jisan = true;
            System.out.println(jisan ? "No" : "Yes");
        }
    }
}

No comments:

Post a Comment