LeetCode:波兰表达式求值(栈)

来源:互联网 发布:node 版本切换 编辑:程序博客网 时间:2024/05/17 21:54

波兰表达式求值

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

解析:遍历输入数组vector首元素直至为空,如果是运算符,分别出运算符栈两个数字,运算得到的结果入栈;如果非运算符,入栈。最后返回栈顶元素即为结果。

#include<stack>#include<string>#include<sstream>#include<vector>class Solution {public:    int evalRPN(vector<string> &tokens) {        stack<int> expression;        string current;        int pre,post,result;        stringstream stream;        while(tokens.size()>0)        {            vector<string>::iterator it=tokens.begin();            current=*it;            tokens.erase(it);            if(current=="+"||current=="-"||current=="/"||current=="*")            {                post=expression.top();                expression.pop();                pre=expression.top();                expression.pop();                if(current=="+")                    result=pre+post;                if(current=="-")                    result=pre-post;                if(current=="/")                    result=pre/post;                if(current=="*")                    result=pre*post;                //stream<<result;                //stream>>current;                expression.push(result);            }            else            {                expression.push(atoi(current.c_str()));            }                     }        return expression.top();    }};

vector迭代器访问元素总结:

vector<type>tokens;

vector<type>::iterator it;

tokens.begin()指向vector首元素指针;tokens.end()末尾元素下一位置的指针,也就是说tokens.end()-1指向末尾元素地址,这里的减1实际上减size(type)


字符串转整数的几种方法总结(string str;):
1. int integer = atoi(str.c_str()); //使用cstdlib/stdlib.h库中的atoi函数
2. stoi(str, nullptr, 10); //仅适用于c++11及其之后的编译器,后两个参数可以不用,默认转换为10进制,可以设定最后一个参数进行控制

3.#include< sstream>

stringstream ss;

   ss << str;
   int integer;
   ss >> integer;

原创粉丝点击