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

    题目

    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

    原题地址

    解题思路

    计算逆波兰表达式。了解很多其它关于逆波兰表达式请点击

    计算逆波兰表达式这是个非常典型的栈应用的样例。

    解题方法就是用栈来处理。须要注意的是本题输入给的是字符串数组,所以须要在字符串和整数之间有个转换。

    代码例如以下

    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            int ret=0;
            int n = tokens.size();
            if(n<=0) return ret;
            stack<int> s;
            int i=0;
            while(i<n){
                string temp = tokens[i];
                int num = atoi(temp.c_str());
                //防止非法输入
                if(num!=0 || (num==0 && temp[0]=='0')){
                    s.push(num);
                }else{
                    ret = cal(s, tokens[i][0]);
                    if(ret == -1) return 0;
                }
                ++i;
            }
            if(!s.empty()) return s.top();
            else return 0;
        }
        int cal(stack<int> &s, char oper){
            if(s.size()<2) return -1;
            int op1 = s.top(); s.pop();
            int op2 = s.top(); s.pop();
            if(oper == '+'){
                s.push(op1+op2);
            }else if(oper == '-'){
                s.push(op2-op1);
            }else if(oper == '*'){
                s.push(op2 * op1);
            }else if(oper == '/'){
                if(op1 == 0) return -1;
                s.push(op2 / op1);
            }else return -1;
            return 0;
        }
    };
    

    假设你认为本篇对你有收获。请帮顶。


    另外。我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.

    你能够搜索公众号:swalge 或者扫描下方二维码关注我

    (转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28243489 )

查看全文
  • 相关阅读:
    2-6 求阶乘序列前N项和
    2-5 求平方根序列前N项和
    2-4 求交错序列前N项和
    2-3 求平方与倒数序列的部分和
    2-2 阶梯电价
    2-1 求整数均值
    2-17 生成3的乘方表
    【秋招之行】自白篇
    Django开发个人博客入门学习经验贴
    浅尝装饰器和AOP
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10482045.html
  • Copyright © 2011-2022 走看看