Problem:
Hint:
先将中缀表达式转化为后缀表达式,然后计算后缀表达式的值
AcCode:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main{
//存取运算的优先级
private static HashMap<Character, Integer> map = null;
//初始化
public static void inti() {
map = new HashMap<Character, Integer>();
map.put('(',-1);
map.put('+', 0);
map.put('-', 0);
map.put('*', 1);
map.put('/', 1);
}
public static List<Object> getHz(String str) {
inti();
List<Object> list = new ArrayList<Object>();//最后返回的后缀表达式
char[] temp = new char[str.length()];
int top = 0;//字符数组的长度
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)>='0' && str.charAt(i)<='9') {
int j;
for (j = i; j < temp.length; j++) {
if(!(str.charAt(j)>='0' && str.charAt(j)<='9')) {
break;
}
}
list.add(str.substring(i, j));
i = j-1;
}else if(str.charAt(i)==')') {
while(top>0) {
char tempChar = temp[--top];
if(tempChar=='(') {
break;
}
list.add(tempChar);
}
}else if(str.charAt(i)=='('){
temp[top++] = '(';
}else {
if(top==0) {
temp[top++] = str.charAt(i);
}else {
int tempIndex = top - 1;
char k = temp[tempIndex];//栈顶符号
char thisChar = str.charAt(i);
if(map.get(k)>=map.get(thisChar)) {
top--;
while(map.get(k)>=map.get(thisChar)) {
list.add(k);
if(top-1>=0) {
k = temp[top-1];
if(map.get(k)>=map.get(thisChar)) {
top--;
}
}else {
break;
}
}
temp[top++] = thisChar;
}else {
temp[top++] = thisChar;
}
}
}
}
//添加剩余的符号
while(top>0) {
list.add(temp[--top]);
}
return list;
}
//计算后缀表达式
public static int getResult(List<Object> list) {
int[] nums = new int[list.size()];
int top = 0;
for (int i = 0; i < list.size(); i++) {
if(list.get(i) instanceof String) {
nums[top++] = Integer.valueOf((String)list.get(i));
}else if((Character)list.get(i)=='+') {
int numA = Integer.valueOf(nums[--top]);
int numB = Integer.valueOf(nums[--top]);
nums[top++] = numA+numB;
}else if((Character)list.get(i)=='-') {
int numA = Integer.valueOf(nums[--top]);
int numB = Integer.valueOf(nums[--top]);
nums[top++] = numB-numA;
}else if((Character)list.get(i)=='*') {
int numA = Integer.valueOf(nums[--top]);
int numB = Integer.valueOf(nums[--top]);
nums[top++] = numA*numB;
}else if((Character)list.get(i)=='/') {
int numA = Integer.valueOf(nums[--top]);
int numB = Integer.valueOf(nums[--top]);
nums[top++] = numB/numA;
}
}
return nums[0];
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
List<Object> list = getHz(str);
//System.out.println(list);
System.out.println(getResult(list));
}
}