题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
#include <iostream> #include <string> #include <stack> #include <queue> #include <vector> #include<algorithm> using namespace std; //处理无括号后的运算 含“s”标记符 int helper(vector<string> rec){ vector<string> rec1,rec2; //去除“s”标记符 for(int i=0;i<rec.size();i++){ if(rec[i]!="s"){ rec1.push_back(rec[i]); } } //先乘除 for(int i=0;i<rec1.size();i++){ if(rec1[i]=="*" || rec1[i]=="/"){ int left=stoi(rec2[rec2.size()-1]); int right=stoi(rec1[i+1]); if(rec1[i]=="*"){ rec2[rec2.size()-1]=to_string(left*right); } else{ rec2[rec2.size()-1]=to_string(left/right); } i++; } else{ rec2.push_back(rec1[i]); } } //后加减 int l=stoi(rec2[0]); for(int i=1;i<rec2.size();i=i+2){ if(rec2[i]=="+"){ l+=stoi(rec2[i+1]); } else if(rec2[i]=="-"){ l-=stoi(rec2[i+1]); } } return l; } int main() { string str; vector<string> rec; cin>>str; int begin=0; //数字分割 for(int i=0;i<int(str.size());i++){ if(!isdigit(str[i])){ //负数处理 if(!(str[i]=='-' && ( i==0 || str[i-1]=='(' ))){ if(i>begin){ rec.push_back(str.substr(begin,i-begin)); } string tem=""; tem.push_back(str[i]); rec.push_back(tem); begin=i+1; } } } if(begin<str.size()) rec.push_back(str.substr(begin)); //括号处理 stack <int> l; queue<pair<int,int>> r; for(int i=0;i<rec.size();i++){ if(rec[i]=="("){ l.push(i); } if(rec[i]==")"){ r.push(make_pair(l.top(),i)); l.pop(); } } int left,right; while(!r.empty()){ left=r.front().first; right=r.front().second; r.pop(); vector<string> cur(rec.begin()+left+1,rec.begin()+right); rec[left]=to_string(helper(cur)); for(int i=left+1;i<=right;i++){ rec[i]="s"; } } cout <<helper(rec); }应该属于最容易理解的思路,先分割提取各个运算单元,然后处理括号问题,最后各部分是无括号的加减乘除问题,从左往右 先乘除后加减即可。