leetcode-Evaluate Reverse Polish Notation
来源:互联网 发布:ubuntu安装apache2 php 编辑:程序博客网 时间:2024/06/04 20:04
Question:
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
Solution:
class Solution {public: int evalRPN(vector<string>& tokens) { int len = tokens.size(); int stack[5000]; int top = -1; int t1 = 0; int t2 = 0; for(int i = 0 ; i < len ; i++){ if(top >= 1){ t1 = stack[top]; t2 = stack[top-1]; } switch(tokens[i][0]){ case '+':stack[--top] = t1+t2;break; case '*':stack[--top] = t2*t1;break; case '/':stack[--top] = t2/t1;break; case '-':if(tokens[i].size()==1){ stack[--top] = t2-t1; break; } default: stack[++top] = atoi(tokens[i].c_str()); //stringstream ss; // ss<<tokens[i]; // ss>>stack[++top]; } } return stack[0]; }};
总结:
1、后缀表达式求值,典型的栈应用。相应的还有中缀表达式转换后缀表达式
:使用两个栈,一个存储运算符号,一个存储数字,运算符栈一直要保证栈顶运算符号优先级最大。
2、stringstream最是耗时beat 8%,16ms
改用atoi beat 72%,9ms。效率相差一倍
0 0
- 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
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- Cocos2d-JS中的简易MVC框架指南(一)
- 19.Itrerable,Iterator迭代器的设计
- URAL2065:Different Sums(找规律)
- Gradle for Android
- rabbitmq
- leetcode-Evaluate Reverse Polish Notation
- php+mysql实现的无限极分类
- css 元素居中
- str convert to int
- 云计算Openstack-Liberty版
- 前端总结·基础篇·CSS(一)布局
- 第三届蓝桥杯【省赛试题2】古堡算式
- Codeforces 552C
- 《逆向工程核心原理》<01-08> abex` crackme #2 -Check按钮处理代码的部分分析