FIx Left Parentheses Program using Stacks
Write a program to fix the left parentheses for the given expression properly to form a balanced expression.
---------------------------Program----------------------------------
import java.util.*;
import java.lang.*;
class FixLeftParentheses {
String input="";
FixLeftParentheses(String x){
this.input=x;
}
public String balanceParentheses(){
if(input.length()==0){
return "";
}
if(input.charAt(0)==')'){
return "()";
}
if (input.length()==1) {
return input;
}
if(input.length()<=2){
if(input.charAt(1)==')'){
String output="("+input.charAt(0)+")";
return output;
}
}
Stack<Character> operators = new Stack<Character>();
Stack<String> operands = new Stack<String>();
for (int i = 0; i < input.length(); i++){
switch (input.charAt(i)){
case '+':
case '-': // Operator case
case '*':
case '/':
operators.push(input.charAt(i));
break;
case '0':
case '1':
case '2':
case '3':
case '4': // "operand" case
case '5':
case '6':
case '7':
case '8':
case '9':
String s = "";
s += input.charAt(i);
operands.push(s);
break;
case ')':
// closing paren case
String a,b;
char c;
if(operands.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Expression not clear");
}else{
a = operands.pop();
}
if(operands.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Expression not clear");
}else{
b = operands.pop();
}
if(operators.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Expression not clear");
}else{
c = operators.pop();
}
StringBuilder buf = new StringBuilder();
buf.append("(");
buf.append(b);
buf.append(c);
buf.append(a);
buf.append(")");
operands.push(buf.toString());
break;
case ' ':
break;
}
}
return operands.pop();
}
public static void main(String[] args){
FixLeftParentheses obj = new FixLeftParentheses("2+3)*5+6)*7+8))");
String output=obj.balanceParentheses();
System.out.println(output);
}
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment