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));
        }
    };
    
  • 相关阅读:
    DHCP Option 60 的理解
    程序中的魔鬼数字
    开源GUI-Microwindows之程序入口分析
    http报错之return error code:401 unauthorized
    内存泄漏以及常见的解决方法
    怎样对ListView的项进行排序
    getline函数
    JavaFx初探
    ListBox控件的操作与实现
    SQLite的SQL语法
  • 原文地址:https://www.cnblogs.com/littlepage/p/14457042.html
Copyright © 2011-2022 走看看