首页 > 代码库 > 【Leetcode】Evaluate Reverse Polish Notation
【Leetcode】Evaluate Reverse Polish Notation
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
1st ( 9 tries )
class Solution {public: bool isnum(string &s) { bool minus = false; if(s[0] == ‘-‘) minus = true; if(minus) { if(s.length() == 1) return false; else { for(int i = 1;i < s.length();i++) { if(s[i] < ‘0‘ || s[i] > ‘9‘) return false; } return true; } } else { for(int i = 0;i < s.length();i++) { if(s[i] < ‘0‘ || s[i] > ‘9‘) return false; } return true; } } int evalRPN(vector<string> &tokens) { stack<string> numst; for(int i = 0;i < tokens.size();i++) { if(isnum(tokens[i])) { numst.push(tokens[i]); } else { int r = atoi(numst.top().c_str()); numst.pop(); int l = atoi(numst.top().c_str()); numst.pop(); int re = 0; if(tokens[i] == "+") { re = l+r; } if(tokens[i] == "-") { re = l-r; } if(tokens[i] == "*") { re = l*r; } if(tokens[i] == "/") { re = l/r; } stringstream ss; ss<<re; numst.push(ss.str()); } } int re = atoi(numst.top().c_str()); return re; }};
2nd (1 tries)
class Solution {public: int evalRPN(vector<string> &tokens) { stack<int> st; for(int i = 0;i < tokens.size();i++) { if(tokens[i] == "+") { int right = st.top(); st.pop(); int left = st.top(); st.pop(); st.push(left+right); } else if(tokens[i] == "-") { int right = st.top(); st.pop(); int left = st.top(); st.pop(); st.push(left-right); } else if(tokens[i] == "*") { int right = st.top(); st.pop(); int left = st.top(); st.pop(); st.push(left*right); } else if(tokens[i] == "/") { int right = st.top(); st.pop(); int left = st.top(); st.pop(); st.push(left/right); } else { int number = atoi( tokens[i].c_str() ); st.push(number); } } return st.top(); }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。