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