Checking balanced parenthesis string I recently wrote a code in online recruitment test. It was very good.

With each question, there were associated space and time limits check. If our code executed correctly within both limits, only then we were given full marks otherwise 0.

Input: String consisting of ASCII characters.

Output: True if the string is balanced parenthesis wise and false otherwise.

I wrote the following code for the problem, but the problem is I got 0 marks because it said limits crossed, Optimization required. 

import java.util.*;
import java.io.*;
class Prths
{
 private static Stack&lt;Boolean&gt; st=new Stack&lt;Boolean&gt;();
 public static void main(String []args)throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();
     boolean result=check(s);
     System.out.println(result);
 }
 public static boolean check(String s)
 {
     int i=0;
     while(i&lt;s.length())
     {
         if(s.charAt(i)==')'&amp;&amp;st.isEmpty())
          return false;
         else if(s.charAt(i)==')')
          st.pop();
         else if(s.charAt(i)=='(')
          st.push(true);
         ++i;
     }
     if(st.isEmpty())
      return true;
     else return false;
 }
}
if(st.isEmpty())
  return true;
 else return false;


This can be simplified to return st.isEmpty();... Wait, that's not the right advice.

Why do you even need a Stack when you can simply count?

public static boolean check(String s) {
    int counter = 0;
    for (int i = 0; i &lt; s.length(); i++) {
        if (s.charAt(i) == '(') {
            counter++;
        } else if (s.charAt(i) == ')') {
            if (counter == 0) {
                return false;
            }
            counter--;
        }
    }
    return counter == 0;
}


Other issues (which may or may not be picked up by the automatic assessment):


If this is assessed using Java 7, using try-with-resources is recommended for the BufferedReader instance.
You can inline the printing of the results, i.e. System.out.println(check(input));.
Please use braces consistently... that tends to improve code readability for human programmers.


edit: OK, second stab at a Java 8 stream-based solution...

// Using better-suited visibility modifier and method name
private static boolean balanced(String input) {
    return input.chars().mapToDouble(i -&gt; i == '(' ? 1 : i == ')' ? -1 : 0).reduce(0,
            (a, b) -&gt; a == 0 &amp;&amp; b == -1 ? Double.NaN : a + b) == 0;
}


mapToDouble() is used here just so that Double.NaN can be used as a special placeholder to effectively ignore further computations when a ) is encountered without a matching (. It doesn't look as streamlined as I hoped it would be though, and I think for most intent and purposes the non-stream-based way works and reads just a little better.