I've been trying to solve this question on SPOJ: http://ift.tt/1EjZOR4.
I've tried to implement a two Stack solution for the problem stated above. It works fine on my system, but I get a 'Wrong Answer' every time I try to submit the following code to the SPOJ Engine.
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class InfixToPostfix {
public static String postfixString(String expression) {
Stack <Character> valueStack = new Stack <Character>();
Stack <Character> operatorStack = new Stack <Character>();
char[] tokens = expression.toCharArray();
for(char c : tokens) {
if(c == '('){
continue;
}
else if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
operatorStack.push(c);
continue;
}
else if(c == ')') {
valueStack.push(operatorStack.peek());
operatorStack.pop();
continue;
}
else {
valueStack.push(c);
continue;
}
}
return valueStack.toString();
}
public static void main (String [] args)throws java.lang.Exception {
String inputString = "";
int n1;
Scanner numberOfTestCases = new Scanner(System.in);
try
{
n1 = numberOfTestCases.nextInt();
StringBuilder[] sbuf = new StringBuilder[n1];
Scanner inputExpression = new Scanner(System.in);
for(int i = 0; i < n1; i++) {
sbuf[i] = new StringBuilder();
if(inputExpression.hasNextLine()) {
inputString = inputExpression.nextLine();
sbuf[i].append(postfixString(inputString).replaceAll("\\[", "").replaceAll("]", "").replaceAll(", ", ""));
}
else {
break;
}
}
for(int i = 0; i < n1; i++) {
System.out.println(sbuf[i].toString());
}
}
catch (Exception e) {
// System.out.println("");
System.out.println(e.getMessage());
// numberOfTestCases.next();
}
System.exit(0);
}
}
I can't figure out where I'm going wrong; I've tried all possible test cases.
P.S.: The problem assumes all inputs to be parenthesized; there's no need to include any code for resolving operator precedence.
Aucun commentaire:
Enregistrer un commentaire