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));
    }
};
posted @ 2021-02-27 20:18  SteveYu  阅读(138)  评论(0编辑  收藏  举报