zoukankan      html  css  js  c++  java
  • [LeetCode] Evaluate Reverse Polish Notation stack 栈

    Evaluate the value of an arithmetic expression in Reverse Polish Notation.

    Valid operators are +-*/. Each operand may be an integer or another expression.

    Some examples:

      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
      ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
    
    Hide Tags
     Stack
     

        题目是用 stack 维护一个公式的进出,判断方法还可以,开始忘记数可能为负,后面改进了。
     
    #include <stack>
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            int n = tokens.size();
            stack<int > tmp;
            for(int i=0;i<n;i++){
                if(tokens[i][0]>='0'&&tokens[i][0]<='9'){
                    tmp.push( helpFun(tokens[i]) );
                    continue;
                }
                if(tokens[i][0]=='-'&&tokens[i][1]!=''){
                    tmp.push( helpFun( tokens[i]));
                    continue;
                }
                int rgt = tmp.top();
                tmp.pop();
                int lft = tmp.top();
                tmp.pop();
                switch (tokens[i][0]){
                case '+':
                    tmp.push( lft + rgt );
                    break;
                case '-':
                    tmp.push(lft - rgt);
                    break;
                case '*':
                    tmp.push(lft * rgt);
                    break;
                case '/':
                    tmp.push(lft / rgt);
                    break;
                }
            }
            return tmp.top();
        }
    
        int helpFun(string str)
        {
            int sum = 0,i = 0;
            if (str[0]=='-')
                i = 1;
            for(;i<str.length();i++)
                sum = sum*10+str[i]-'0';
            return str[0]=='-'?-sum:sum;
        }
    };
    
    int main()
    {
        vector<string> tokens{"3","-4","+"};
        Solution sol;
        cout<<sol.evalRPN(tokens)<<endl;
    //    for(int i=0;i<tokens.size();i++)
    //        cout<<tokens[i]<<endl;
        return 0;
    }
  • 相关阅读:
    开启Tomcat APR运行模式,优化并发性能
    KVM与XEN虚拟化环境究竟有何不同
    fio测试freenas共享的iscsi磁盘性能
    ubuntu 16.04网速监控脚本
    centos 7网速监控脚本
    ubuntu 16.04 配置远程连接
    iometer测试磁盘IO性能
    pip 使用豆瓣源
    raid write back / write throught
    卡常数技巧
  • 原文地址:https://www.cnblogs.com/Azhu/p/4345832.html
Copyright © 2011-2022 走看看