题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String s = br.readLine();
s = s.replaceAll("\\{", "(");
s = s.replaceAll("\\}", ")");
s = s.replaceAll("\\[", "(");
s = s.replaceAll("\\]", ")");
System.out.println(resolve(s));
} catch (IOException e) {
e.printStackTrace();
}
}
public static int resolve(String str) {
char sign = '+';
int num = 0;
Stack<Integer> stack = new Stack();
int length = str.length();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (c == ' ')continue; //注意点3,需要处理空字符
if (Character.isDigit(c)) {
//num = c-'0';//注意点2,若遇到大于9的数,这个地方没有处理
num = 10 * num + c -'0';
} else if (c == '(') {
int j = i + 1;
//注意点4,无法处理括号嵌套{[()]},首先需要在程序最开始将所有{}[]替换为()
//其次需要在这里找出最外层左括号对应的最外层右括号
/* while (str.charAt(j)!=')'){
j++;
}*/
int count = 1;
while (count > 0) {
if (str.charAt(j) == ')') {
count--;
} else if (str.charAt(j) == '(') {
count++;
}
j++;
}
num = resolve(str.substring(i + 1, j - 1));
i = j - 1; //注意点1,需要更新i的索引为右括号的索引,这样可以保证括号内的计算结果在下边可以加入栈
}
if (!Character.isDigit(c) || i == length - 1) {
switch (sign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(num * (-1));
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
num = 0;
sign = c;
}
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
查看7道真题和解析