题目
题目链接:
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
思路
本题非常难。递归处理
题解:使用栈模拟即可,遇到右括号时,一直运算到出现左括号,
当遇到运算符时,需要进行判断,当前c的优先级不高于栈顶就进行运算。
参考答案
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
return f(s.toCharArray(), 0).val;
}
public static Info f(char[] strs, int i) {
LinkedList<String> ll = new LinkedList<>();
int cur = 0;
Info info = new Info();
for (; i < strs.length && strs[i] != ')'; ) {
char str = strs[i];
if (str == ' ') {
i++;
continue;
}
if (str >= '0' && str <= '9') {
cur = cur * 10 + (int) (str - '0');
i++;
} else if (str != '(') { //遇到运算符了
addNum(ll, cur);
ll.addLast(str + "");
i++;
cur = 0;
} else {
info = f(strs, i + 1);
i = info.index + 1;
cur = info.val;
}
}
addNum(ll, cur);
info.val = getRet(ll);
info.index = i;
return info;
}
public static int getRet(LinkedList<String> ll) {
int res = 0;
boolean add = true;
while (!ll.isEmpty()) {
String top = ll.pollFirst();
if (top.equals("+")) add = true;
else if (top.equals("-")) add = false;
else {
if (add) res += Integer.valueOf(top);
else res -= Integer.valueOf(top);
}
}
return res;
}
public static void addNum(LinkedList<String> ll, int num) {
if (!ll.isEmpty()) {
String top = ll.pollLast();
int cur = 0;
if (top.equals("+") || top.equals("-"))
ll.addLast(top);
else {
cur = Integer.valueOf(ll.pollLast());
if (top.equals("*")) num = cur * num;
else num = cur / num;
}
}
ll.addLast(String.valueOf(num));
}
static class Info {
int val;
int index;
}
}