首页 > 学院 > 开发设计 > 正文

150. Evaluate Reverse Polish Notation

2019-11-08 03:20:32
字体:
来源:转载
供稿:网友

简单题,直接用栈搞定

class Solution {public: int evalRPN(vector<string>& tokens) { stack<int>st; for(int i = 0; i < tokens.size(); ++ i){ if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){ int a, b, c; a = st.top(); st.pop(); b = st.top(); st.pop(); if(tokens[i] == "+") c = b + a; else if(tokens[i] == "-") c = b - a; else if(tokens[i] == "*") c = b * a; else c = b / a; st.push(c); } else{ int a = 0; int f = 1; int j = 0; string t = tokens[i]; if(t[0] == '-'){ f = -1; j = 1; } for(; j < t.length(); ++ j){ a = a * 10 + t[j] - '0'; } st.push(a * f); } } return st.top(); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表