#include<iostream>#include<stack>#include<string>#include<cctype>usingnamespace std;// 判断运算符优先级intpriority(char op){if(op =='*'|| op =='/')return2;if(op =='+'|| op =='-')return1;return0;}intcalculate(string s){
stack<int> nums;
stack<char> ops;for(int i =0; i < s.length(); i++){if(s[i]==' ')continue;if(isdigit(s[i])){int num =0;while(i < s.length()&&isdigit(s[i])){
num = num *10+(s[i]-'0');
i++;}
i--;
nums.push(num);}elseif(s[i]=='('){
ops.push(s[i]);}elseif(s[i]==')'){while(!ops.empty()&& ops.top()!='('){char op = ops.top();
ops.pop();int b = nums.top(); nums.pop();int a = nums.top(); nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}
ops.pop();// 弹出 '('}else{// 运算符while(!ops.empty()&& ops.top()!='('&&priority(ops.top())>=priority(s[i])){char op = ops.top();
ops.pop();int b = nums.top(); nums.pop();int a = nums.top(); nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}
ops.push(s[i]);}}while(!ops.empty()){char op = ops.top();
ops.pop();int b = nums.top(); nums.pop();int a = nums.top(); nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}return nums.top();}intmain(){
string expr;getline(cin, expr);
cout <<calculate(expr)<< endl;return0;}
importjava.util.*;publicclassMain{// 判断运算符优先级privatestaticintpriority(char op){if(op =='*'|| op =='/')return2;if(op =='+'|| op =='-')return1;return0;}publicstaticintcalculate(String s){Stack<Integer> nums =newStack<>();Stack<Character> ops =newStack<>();for(int i =0; i < s.length(); i++){char c = s.charAt(i);if(c ==' ')continue;if(Character.isDigit(c)){int num =0;while(i < s.length()&&Character.isDigit(s.charAt(i))){
num = num *10+(s.charAt(i)-'0');
i++;}
i--;
nums.push(num);}elseif(c =='('){
ops.push(c);}elseif(c ==')'){while(!ops.empty()&& ops.peek()!='('){char op = ops.pop();int b = nums.pop();int a = nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}
ops.pop();// 弹出 '('}else{// 运算符while(!ops.empty()&& ops.peek()!='('&&priority(ops.peek())>=priority(c)){char op = ops.pop();int b = nums.pop();int a = nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}
ops.push(c);}}while(!ops.empty()){char op = ops.pop();int b = nums.pop();int a = nums.pop();if(op =='+') nums.push(a + b);elseif(op =='-') nums.push(a - b);elseif(op =='*') nums.push(a * b);elseif(op =='/') nums.push(a / b);}return nums.peek();}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);String expr = sc.nextLine();System.out.println(calculate(expr));}}
defpriority(op):if op in['*','/']:return2if op in['+','-']:return1return0defcalculate(s):
nums =[]# 数字栈
ops =[]# 运算符栈
i =0while i <len(s):if s[i]==' ':
i +=1continueif s[i].isdigit():# 数字
num =0while i <len(s)and s[i].isdigit():
num = num *10+int(s[i])
i +=1
nums.append(num)continueif s[i]=='(':# 左括号
ops.append(s[i])elif s[i]==')':# 右括号while ops and ops[-1]!='(':
op = ops.pop()
b = nums.pop()
a = nums.pop()if op =='+': nums.append(a + b)elif op =='-': nums.append(a - b)elif op =='*': nums.append(a * b)elif op =='/': nums.append(a // b)
ops.pop()# 弹出 '('else:# 运算符while ops and ops[-1]!='('and priority(ops[-1])>= priority(s[i]):
op = ops.pop()
b = nums.pop()
a = nums.pop()if op =='+': nums.append(a + b)elif op =='-': nums.append(a - b)elif op =='*': nums.append(a * b)elif op =='/': nums.append(a // b)
ops.append(s[i])
i +=1while ops:
op = ops.pop()
b = nums.pop()
a = nums.pop()if op =='+': nums.append(a + b)elif op =='-': nums.append(a - b)elif op =='*': nums.append(a * b)elif op =='/': nums.append(a // b)return nums[0]
expr =input()print(calculate(expr))
算法及复杂度
算法:栈实现的四则运算表达式求值
时间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n) - 其中
n
n
n 为表达式的长度
空间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n) - 需要两个栈来存储数字和运算符