首页 > 代码库 > LeetCode Evaluate Reverse Polish Notation
LeetCode Evaluate Reverse Polish Notation
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; }};
数据结构栈基础,一次过
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。