是否有AC過的人能給些意見呢?
我的code自己怎麼測,答案都沒問題.但在此執行總是WA...
麻煩有空閒的人幫忙分析一下:)
[code]
import java.util.LinkedList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
try{
String str=null;
String ch="";
while((str=in.nextLine())!=null){
LinkedList<String> stack=new LinkedList<String>();
int index=0;
stack.add(null);
String array[]=str.split(" ");
String postfix[]=new String[array.length];
for(int i=0;i<array.length;i++){
ch=array[i];
if("(".equals(ch)){
stack.add(ch);
}else if("-".equals(ch) || "+".equals(ch) || "*".equals(ch) || "/".equals(ch) || "%".equals(ch)){
if(priority(stack.getLast()) >= priority(ch)){
postfix[index]=stack.removeLast();
index++;
}
stack.add(ch);
}else if(")".equals(ch)){
while(!"(".equals(stack.getLast())){
postfix[index]=stack.removeLast();
index++;
}
stack.removeLast();
}else{
postfix[index]=ch;
index++;
}
}
while(stack.getLast()!=null){
postfix[index]=stack.removeLast();
index++;
}
stack=new LinkedList<String>();
for(int i=0;i<index;i++){
ch=postfix[i];
if("-".equals(ch) || "+".equals(ch) || "*".equals(ch) || "/".equals(ch) || "%".equals(ch)){
stack.add(calculate(stack.removeLast(),stack.removeLast(),ch));
}else{
stack.add(ch);
}
}
System.out.println(stack.removeLast());
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static int priority(String op){
if("+".equals(op) || "-".equals(op)){
return 1;
}else if("*".equals(op) || "/".equals(op) || "%".equals(op)){
return 2;
}
return 0;
}
public static String calculate(String a,String b, String operand){
int sum=0,var2=Integer.parseInt(a),var1=Integer.parseInt(b);
if("+".equals(operand)){
sum=var1+var2;
}else if("-".equals(operand)){
sum=var1-var2;
}else if("*".equals(operand)){
sum=var1*var2;
}
else if("/".equals(operand)){
sum=var1/var2;
}else if("%".equals(operand)){
sum=var1%var2;
}
return String.valueOf(sum);
}
}
[/code]