In: Computer Science
parse(“{3 + {4/2} }”) would return -1
parse(“{ { 4*X}”) would return 6 since at position 6 we expected another “}”
parse(“{3+4}}”) would also return a 6
import java.util.*;
import java.io.*;
class IntegerStack {
}
class StaticStack {
private int size;
private Stack<Character> stack1 = new Stack<Character>();
StaticStack() {
size = 10;
}
StaticStack(int size) {
this.size = size;
}
void push(char x) {
if(isFull()) {
System.out.println("Stack is Full!");
return ;
}
size++;
stack1.push(x);
}
int pop() {
if(isEmpty()) {
System.out.print("Stack is Empty!");
return -1;
}
size--;
return stack1.pop();
}
boolean isEmpty() {
return stack1.empty();
}
boolean isFull() {
return size == stack1.size();
}
}
class Main {
static int parse(String exp) {
StaticStack s = new StaticStack();
int i;
for(i=0;i<exp.length();++i) {
if(exp.charAt(i)=='{' || exp.charAt(i)=='(')
s.push(exp.charAt(i));
else if(exp.charAt(i)=='}') {
if(s.isEmpty()) {
s.push('}');
i++;
break;
}
if(s.pop()!='{') {
break;
}
}else if(exp.charAt(i) == ')') {
if(s.isEmpty()) {
s.push('}');
i++;
break;
}
if(s.pop()!='(') {
break;
}
}
}
if(s.isEmpty())
return -1;
return i;
}
public static void main(String args[]) {
System.out.println(parse("{3+{4/2}}"));
System.out.println(parse("{{4*X}"));
System.out.println(parse("{3+4}}"));
// StaticStack s = new StaticStack();
//
// s.push('A');
// System.out.println(s.pop());
}
}
OUTPUT: