题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
#include <stack> #include <cstring> #include <string> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ bool equal(char a,stack<char> &temp4) { if(a=='+'||a=='-') { if(temp4.top()=='+'||temp4.top()=='-') return true; else return false;; } else { if(temp4.top()=='*'||temp4.top()=='/') return true; else return false;; } } bool lower(char a,stack<char> &s_temp) { if (a=='*' || a=='/') { return false; } else { if(s_temp.top()=='+' || s_temp.top()=='-') { return false; } else { return true; } } } void calc(stack<int>&num_temp,stack<char>s_temp) { int temp2 = num_temp.top(); num_temp.pop(); int temp1 = num_temp.top(); num_temp.pop(); switch (s_temp.top()) { case '+':num_temp.push(temp1+temp2);break; case '-':num_temp.push(temp1-temp2);break; case '*':num_temp.push(temp1*temp2);break; case '/':num_temp.push(temp1/temp2);break; default:break; } } int solve(string s) { // write code here stack<int> num; stack<char> oper; string temp3; int length = s.length(); for(int i=0;i<length;i++) { if(s[i]=='('||s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/' ||s[i]==')') { if(!oper.empty() && lower(s[i],oper) &&s[i]!='('&&s[i]!=')') { while (!oper.empty() && oper.top()!='(') { calc(num,oper); oper.pop(); } oper.push(s[i]); }//上面代码计算的是优先级情况 else if (!oper.empty()&&s[i]!='('&&s[i]!=')'&&equal(s[i],oper)) { calc(num, oper); oper.pop(); oper.push(s[i]); }//此段代码计算的是优先级相同 else if (s[i]==')') { while (oper.top()!='(') { calc(num,oper); oper.pop(); } oper.pop(); }//此段代码计算的右括号端,该段没有push操作,因为不讲右括号入栈 else { oper.push(s[i]); }//其他情况运算法正常入栈 } else { while (s[i]!='('&&s[i]!='+'&&s[i]!='-'&&s[i]!='*'&&s[i]!='/' && s[i]!=')'&&i<length) { temp3+=s[i]; i++; }//获得大于一位的数字并入栈 num.push(stoi(temp3)); temp3={}; i--; } if(i==length-1 && !oper.empty()) { calc(num, oper); oper.pop(); }//如果到最后操作符栈还没空时,则将操作符全部执行 } // return num.top(); } };