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;
    }
  • 相关阅读:
    java中的死锁现象
    Maven 创建动态web 3.0项目
    查询数据库主外键关系
    函数指针的应用学习Demo
    WCF宿主Window Service Demo
    一段小程序理解getchar和putchar
    Flash在线签名小程序,可回放,动态导出gif图片
    uninstall gitlab
    使用SCP在命令行传输文件
    Linux下网卡eth编号配置文件路径
  • 原文地址:https://www.cnblogs.com/Azhu/p/4345832.html
Copyright © 2011-2022 走看看