zoukankan      html  css  js  c++  java
  • 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));
        }
    };
    
  • 相关阅读:
    go装饰器
    python属性描述符和属性查找过程
    python property动态属性
    python中is 与 ==的区别
    python变量到底是什么
    python对象的可变性
    python sorted函数
    《Note --- UE4 --- Blueprint_Overview_HowTo》
    《Temporal AA , SMAA and MSAA》
    TODO
  • 原文地址:https://www.cnblogs.com/littlepage/p/14457042.html
Copyright © 2011-2022 走看看