码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Evaluate Reverse Polish Notation

时间:2014-07-22 22:45:14      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   数据   io   for   

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        int len = tokens.size();
        if (len < 1) return 0;
        
        vector<int> stack;
        for (int i=0; i<len; i++) {
            string &p = tokens[i];
            if (p[0] >= 0 && p[0] <= 9 || p[0] == - && p.size() > 1) {
                stack.push_back(stoi(p));
            } else {
                int slen = stack.size();
                stack[slen - 2] = op(p[0], stack[slen - 2], stack[slen - 1]);
                stack.pop_back();
            }
        }

        return stack[0];
    }
    
    int op(const char op, int a, int b) {
        int res = 0;
        switch(op) {
            case +: res = a + b; break;
            case -: res = a - b; break;
            case /: res = a / b; break;
            case *: res = a * b; break;
        }
        return res;
    }
    
    int stoi(string &s) {
        int len = s.size();
        if (len < 1) return 0;
        bool neg = s[0] == -;
        int i = neg ? 1 : 0;
        int res = 0;
        while (i < len) {
            res = res * 10 + s[i] - 0;
            i++;
        }
        return neg ? -res : res;
    }
};

数据结构栈基础,一次过

LeetCode Evaluate Reverse Polish Notation,布布扣,bubuko.com

LeetCode Evaluate Reverse Polish Notation

标签:style   blog   color   数据   io   for   

原文地址:http://www.cnblogs.com/lailailai/p/3860048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!