题目
题目链接:
https://www.nowcoder.com/practice/a9c170bfaf7349e3acb475d786ab1c7d
核心
DFS+双端队列
参考答案Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int calculate (String s) {
//dfs,队列
return dfs(s, 0).val;
}
//当前来到s的i位置。
public Info dfs(String s, int i) {
LinkedList<String> ll = new LinkedList<>();
int cur = 0;
Info info = new Info();
while (i < s.length() && s.charAt(i) != ')') {
char c = s.charAt(i);
if (c == ' ') {
i++;
continue;
}
if (c >= '0' && c <= '9') {
cur = cur * 10 + (c - '0');
i++;
} else if (c != '(') { //遇到运算符了
addNum(ll, cur);
ll.addLast(c + "");
i++;
cur = 0;
} else {
info = dfs(s, i + 1);
i = info.index + 1;
cur = info.val;
}
}
addNum(ll, cur);
info.val = getRes(ll);
info.index = i;
return info;
}
public int getRes(LinkedList<String> ll) {
int res = 0;
boolean add = true;
String cur;
while (!ll.isEmpty()) {
cur = ll.pollFirst();
if (cur.equals("+")) add = true;
else if (cur.equals("-")) add = false;
else {
if (add) res += Integer.valueOf(cur);
else res -= Integer.valueOf(cur);
}
}
return res;
}
public void addNum(LinkedList<String> ll, int num) {
if (!ll.isEmpty()) {
String top = ll.pollLast();
if (top.equals("+") || top.equals("-")) {
ll.addLast(top);
} else {
int cur = Integer.valueOf(ll.pollLast());
if (top.equals("*")) num = cur * num;
else num = cur / num;
}
}
ll.addLast(num + "");
}
static class Info {
int index;
int val;
}
}