A slightly different approach I took to solve this problem, I have observed two key points in this problem.
So I converted these points into easy-to-implement and understandable format.
For Example : "{ } ( ) [ ]" will be "1 -1 2 -2 3 -3" is valid parenthesis. For a balanced parenthesis, positives can be adjacent where as a negative number should be of positive number in top of the stack.
Below is code:
import java.util.Stack;
public class Main {
public static void main (String [] args)
{
String value = "()(){}{}{()}";
System.out.println(Main.balancedParanthesis(value));
}
public static boolean balancedParanthesis(String s) {
char[] charArray=s.toCharArray();
int[] integerArray=new int[charArray.length];
// creating braces with equivalent numeric values
for(int i=0;i<charArray.length;i++) {
if(charArray[i]=='{') {
integerArray[i]=1;
}
else if(charArray[i]=='}') {
integerArray[i]=-1;
}
else if(charArray[i]=='[') {
integerArray[i]=2;
}
else if(charArray[i]==']') {
integerArray[i]=-2;
}
else if(charArray[i]=='(') {
integerArray[i]=3;
}
else {
integerArray[i]=-3;
}
}
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<charArray.length;i++) {
if(stack.isEmpty()) {
if(integerArray[i]<0) {
stack.push(integerArray[i]);
break;
}
stack.push(integerArray[i]);
}
else{
if(integerArray[i]>0) {
stack.push(integerArray[i]);
}
else {
if(stack.peek()==-(integerArray[i])) {
stack.pop();
}
else {
break;
}
}
}
}
return stack.isEmpty();
}
}