题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static String s = "";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
s = in.next();
}
result();
}
private static void result() {
split();
int result = sum(s);
System.out.print(result);
}
public static void split() {
int end = s.replaceFirst("\\)", "b").indexOf("b");
int start = -1;
for (int i = end - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c == '(') {
start = i;
break;
}
}
if (start == -1) {
return;
}
String temp = s.substring(start + 1, end);
int sum = sum(temp);
String s1 = s.replace("(" + temp + ")", sum<0? ("a"+(-sum)) : (sum + ""));
s = s1;
split();
}
private static int sum(String temp) {
Node1 root = new Node1();
Node1 tNode = new Node1();
root.eqList.add(tNode);
int len = temp.length();
for (int i = 0; i < len; i++) {
char c = temp.charAt(i);
if (c >= '0' && c <= '9') {
int ci = (int) c - 48;
int d = tNode.data * 10 + (tNode.symbol ? ci : -ci);
tNode.data = d;
continue;
}
if (i == 0 && c == '-') {
tNode.symbol = false;
continue;
}
if (c == 'a') {
tNode.symbol = !tNode.symbol;
continue;
}
tNode = setNode(root, tNode, c);
}
return root.getResult();
}
private static Node1 setNode(Node1 root, Node1 t, char c) {
if ('*' == c || '/' == c) {
Node1 n = setNextNode(root, t);
t.nextMultSymbol = c == '*';
return n;
} else if ('+' == c || '-' == c) {
Node1 n = setEqNode(root);
if (c == '-') {
n.symbol = false;
}
return n;
} else {
return t;
}
}
private static Node1 setNextNode(Node1 root, Node1 t) {
Node1 n = new Node1();
t.nextNode = n;
return n;
}
private static Node1 setEqNode(Node1 root) {
Node1 n = new Node1();
root.eqList.add(n);
return n;
}
static class Node1 {
public int data = 0;
public boolean symbol = true;
public boolean nextMultSymbol = true;
public List<Node1> eqList = new LinkedList<>();
public Node1 nextNode = null;
public int getEqualSum() {
int sum = eqList.stream().mapToInt(i -> i.getResult()).sum();
return sum;
}
public int getNextResult() {
if (nextNode != null) {
int t = data;
while (nextNode != null) {
if (nextMultSymbol) {
t = t * nextNode.data;
} else {
t = t / nextNode.data;
}
nextNode = nextNode.nextNode;
}
return t;
}
return data;
}
public int getResult() {
int res = getEqualSum() + getNextResult();
return res;
}
}
}
多优化,修复bug
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记