题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
//先把所有括号统一
s = s.replace("{","(");
s = s.replace("[","(");
s = s.replace("}",")");
s = s.replace("]",")");
//初始字符串预处理(提取数字整体作为一个字符串,创建字符串数组,其中包含对负数的处理)
List<String> list = String2List(s);
//中缀表达式转后缀表达式
List<String> ss = mid2back(list);
//后缀表达式计算
System.out.print(backCal(ss));
}
public static List<String> mid2back(List<String> s){
List<String> ss = new ArrayList<>();
Stack<String> stack = new Stack<String>();
for(int i=0; i<s.size(); i++){
String c = s.get(i);
//System.out.println(c);
//数字直接输出,字符判断入栈(请注意:左括号的优先级,入栈后视为最低)
if(isNum(c)){
ss.add(c);
}else{
if(c.equals("(") || stack.isEmpty()){
stack.push(c);
}
else if(c.equals(")")){
//出栈直到碰到左括号
while(!stack.peek().equals("(")){
ss.add(stack.pop());
}
//左括号弹出去
stack.pop();
}
else if(c.equals("*") || c.equals("/")){
//栈顶运算符优先级低于当前操作符,入栈
if(stack.peek().equals("+") || stack.peek().equals("-") || stack.peek().equals("(") ){
stack.push(c);
}else{
//出栈,直到栈顶优先级低于当前操作符,或者栈空,然后入栈
while(!stack.isEmpty() && (stack.peek().equals("*") || stack.peek().equals("/"))){
ss.add(stack.pop());
}
stack.push(c);
}
}
else if(c.equals("+") || c.equals("-")){
if(stack.peek() == "("){
stack.push(c);
}else{
while(!stack.isEmpty() && !stack.peek().equals("(") ){
ss.add(stack.pop());
}
stack.push(c);
}
}
}
}
//如果栈内还有运算符,直接弹出,直到栈空
while(!stack.isEmpty()){
ss.add(stack.pop());
}
//System.out.println(ss);
return ss;
}
public static String backCal(List<String> ss){
//这里必须为String类型,不然后边字符和数字的转换会出现问题
Stack<String> stack = new Stack<>();
for(int i=0; i<ss.size(); i++){
String c = ss.get(i);
//数字直接入栈
if(isNum(c)){
stack.push(c);
}
//运算符,取出来并计算,再放进去
else{
Long b = Long.parseLong(stack.pop());
Long a = Long.parseLong(stack.pop());
switch(c){
case "+":
stack.push(Long.toString(a + b));
break;
case "-":
stack.push(Long.toString(a - b));
break;
case "*":
stack.push(Long.toString(a * b));
break;
case "/":
stack.push(Long.toString(a / b));
break;
}
}
}
return stack.pop();
}
public static boolean isNum(String s){
for(int i = 0; i <= 9; i++){
if(s.contains(i+"")){
return true;
}
}
return false;
}
public static List<String> String2List(String s){
List<String> list = new ArrayList<>();
String temp = "";
for(int i=0; i<s.length();i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
if(i!=s.length()-1 && Character.isDigit(s.charAt(i+1))){
temp += c;
}else{
temp += c;
list.add(temp);
temp = "";
}
}else if(c == '-'){
//对负数特殊处理(如“-4”要当作一个操作数来处理)
if(i == 0 || s.charAt(i-1) == '('){
temp += c;
}else{
list.add(c + "");
}
}else{
list.add(c + "");
}
}
return list;
}
}
