LeetCode(150) Evaluate Reverse Polish Notation
2024-08-30 22:42:13
题目
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
分析
本题考查的是栈的应用,计算后缀表达式的值。
参考数据结构,栈章节。
AC代码
class Solution {
public:
int evalRPN(vector<string>& tokens) {
if (tokens.empty())
return 0;
//存储运算数
stack<int> s;
//tokens容量
int size = tokens.size();
for (int i = 0; i < size; ++i)
{
if (!isOper(tokens[i]))
{
s.push(strToInt(tokens[i]));
}
else{
char op = tokens[i][0];
switch (op)
{
int op1, op2;
case '+':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 + op1);
break;
case '-':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 - op1);
break;
case '*':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 * op1);
break;
case '/':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 / op1);
break;
default:
break;
}//switch
}//else
}//for
return s.top();
}
//判断是否为运算符
bool isOper(string &str)
{
if (str.size() > 1)
return false;
if (str[0] == '+' || str[0] == '-' || str[0] == '*' || str[0] == '/')
return true;
return false;
}
//将字符串转换为整数
int strToInt(string &str)
{
if (str.empty())
return 0;
// 求字符串长度
int size = str.size();
int flag = 1, pos = 0, sum = 0, multi = 1;
if (str[0] == '-')
{
flag = -1;
pos = 1;
}
for (int i = size - 1; i >= pos; --i)
{
sum += (str[i] - '0') * multi;
multi *= 10;
}
return flag * sum;
}
};
最新文章
- PHP引用(&;)使用详解
- atitit 英文与中文与阿拉伯文的简化解决方案.docx
- JPA, JNDI, OSGi
- mongodb3.x版本用户管理方法
- hdu 4010 动态树 @
- shell脚本批量处理字符串
- cas 登陆超时 解决方案
- dump json 显示中文问题
- cocos2d-html5基金会
- DRP项目总结
- JpaManytoMany
- 从拥抱开源到回馈开源,灵雀云助力CNCF中国区培训业务
- 实战操作——通过wireshark查看任意qq好友IP
- Redis学习笔记(1)-安装Oracle VM VirtualBox
- Docker容器中找不到vim命令
- Linux 查看CPU信息,机器型号,内存等信息
- leetcode题解 candy
- 时间处理:计算下一天日期,如输入";2004/12/31";(注释2014年12月31日),则输出";2005/1/1";.
- sublime text syntaxdef
- 面试必备:HashMap源码解析(JDK8)