LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

LeetCode: Reverse Words in a String: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 地址:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

计算波兰后缀表达式的值,具体做法是利用一个栈,如果遇到数字则把数字进栈,如果遇到操作符就把栈中的数字出栈进行运算(二元操作符出栈两个数字,一元操作符出栈一个数字),最后的结果存在栈中。代码:
 class Solution {
public:
int evalRPN(vector<string> &tokens) {
int lop, rop;
vector<string>::const_iterator cIter = tokens.begin();
stack<int> s;
for(; cIter != tokens.end(); ++cIter){
if ((*cIter).size() == && !isdigit((*cIter)[])){
char op = (*cIter)[];
rop = s.top();
s.pop();
lop = s.top();
s.pop();
if ('+' == op){
s.push(lop + rop);
} else if ('-' == op){
s.push(lop - rop);
} else if ('*' == op){
s.push(lop * rop);
} else{
s.push(lop / rop);
}
} else {
s.push(atoi((*cIter).c_str()));
}
}
return s.top();
}
};
上一篇:react 表格扩展与编辑


下一篇:[Xamarin] 調用JSON.net 來解析JSON (转帖)