leetcode第一刷_Evaluate Reverse Polish Notation
来源:互联网 发布:数据分析工作计划 编辑:程序博客网 时间:2024/05/17 06:05
逆波兰表达式在本科时的编译原理有学到过,一看到它,我总是想到栈,这道题我也是这样解的。个人觉得转化成逆波兰比计算逆波兰要更难一些。转化成逆波兰时,要维护一个运算符的栈,运算符优先级从底向上增加,从左到右扫描表达式时,遇到数字直接输出,如果是运算符,则比较它跟栈顶运算符,如果栈顶预算符优先级更高,则出栈直到优先级低于要入栈的元素,然后将这个运算符入栈。对于括号,如果是“(”则直接入栈,如果是“)”,则出栈运算符,直到遇到“(”。
还有一个比较烦人的地方是正负号和加减号之间的问题,如果一个“-”后面跟的是一个数字,也就是这个string的长度大于1,那么就认为它代表的是一个负数。
ac代码如下:
class Solution {public: int changeToInt(string &s){ int res = 0; istringstream stream(s); stream>>res; return res; } bool isNum(string &s){ if((s[0]>='0'&&s[0]<='9')||(s[0]=='-'&&s.length()>1)) return true; return false; } int evalRPN(vector<string> &tokens) { int s[tokens.size()]; int head = -1, index = 0; while(index<tokens.size()){ if(isNum(tokens[index])){ int tp = changeToInt(tokens[index]); s[++head] = tp; }else{ int a = s[head-1]; int b = s[head]; head--; if(tokens[index] == "+") s[head] = a+b; else if(tokens[index] == "-") s[head] = a-b; else if(tokens[index] == "*") s[head] = a*b; else s[head] = a/b; } index++; } return s[0]; }};
0 0
- leetcode第一刷_Evaluate Reverse Polish Notation
- LeetCode第一题:Evaluate Reverse Polish Notation
- leetcode_题解_Evaluate Reverse Polish Notation逆波兰式
- 刷Leetcode:Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- 单独调用Ueditor的图片和附件上传功能
- 《加密与解密》4 PE
- 畅游屏山“那”山水
- java 重定向和转发的区别
- srm615 div2
- leetcode第一刷_Evaluate Reverse Polish Notation
- 加密与解密 5
- 数据结构——AVL树
- 的尽快发货的时间来恢复健康绿色的疯狂了的酸辣粉
- 【学习笔记】浅析TCP的拥塞控制
- SQLConfigDataSource的用法
- java下Class.forName的作用是什么,为什么要使用它
- DLL和EXE的区别
- C++大型项目开发约束