patternjavaModerate
Checking balanced parenthesis string
Viewed 0 times
balancedcheckingstringparenthesis
Problem
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.
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 st=new Stack();
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<s.length())
{
if(s.charAt(i)==')'&&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;
}
}Solution
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 < 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-resourcesis recommended for theBufferedReaderinstance.
- 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 -> i == '(' ? 1 : i == ')' ? -1 : 0).reduce(0,
(a, b) -> a == 0 && 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.Code Snippets
if(st.isEmpty())
return true;
else return false;public static boolean check(String s) {
int counter = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
counter++;
} else if (s.charAt(i) == ')') {
if (counter == 0) {
return false;
}
counter--;
}
}
return counter == 0;
}// Using better-suited visibility modifier and method name
private static boolean balanced(String input) {
return input.chars().mapToDouble(i -> i == '(' ? 1 : i == ')' ? -1 : 0).reduce(0,
(a, b) -> a == 0 && b == -1 ? Double.NaN : a + b) == 0;
}Context
StackExchange Code Review Q#106219, answer score: 12
Revisions (0)
No revisions yet.