evalRPN 逆波蘭算術

#include <iostream> #include <cstring> #include <vector> #include <unordered_map> #include <stack> using namespace std; class Solution { public: int evalRPN(vector<string>&& tokens) { stack<int> nums; for(auto& x: tokens) { if(!isdigit(x[0])) { int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); if(x == "+") nums.push(a + b); else if(x == "-") nums.push(a - b); else if(x == "*") nums.push(a * b); else if(x == "/") nums.push(a / b); } else nums.push(stoi(x)); } return nums.top(); } vector<string> toRPN(string& s) { unordered_map<string, int> pr{{"*", 2}, {"/", 2}, {"+", 1}, {"-", 1}}; vector<string> ans; stack<string> ops; if(!s.size()) return ans; s.insert(0, 1, '('); s.push_back(')'); for(int i = 0; i < s.size(); i++) { if(isdigit(s[i])) { string cur = ""; while(i < s.size() && isdigit(s[i])) cur += s[i++]; i--; ans.push_back(cur); } else if(s[i] == '(') ops.push("("); else if(s[i] == ')') { while(ops.top() != "(") { ans.push_back(ops.top()); ops.pop(); } ops.pop(); } else { string cur = string(1, s[i]); if(ops.empty() || pr[cur] > pr[ops.top()]) ops.push(cur); else { while(!ops.empty()) { if(pr[cur] <= pr[ops.top()]) { ans.push_back(ops.top()); ops.pop(); } else break; } ops.push(cur); } } } return ans; } int solve(string s) { return evalRPN(toRPN(s)); } };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章