【leetcode】Evaluate Reverse Polish Notation

本文详细介绍了如何利用栈数据结构解决中缀表达式转后缀表达式的问题,并通过实例展示了如何进行求值过程。重点突出了字符串转整数的效率比较和代码实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用栈实现比较简单,遇到数字压栈,遇到运算符号两次出栈运算,再将结果压栈,遍历一次vector即可。

注意:将字符串转为int时,使用atoi可以accept,但用自己编写的转换函数会超时。


//2014年8月20日20:35:12
//2014年8月20日21:08:26

#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> st;
        for(vector<string>::size_type i=0 ; i<tokens.size() ; i++){
            if(tokens[i] == "+"){
                int b = st.top();
                st.pop();
                int a = st.top();
                st.pop();
                st.push(a + b);
            }
            else if(tokens[i] == "-"){
                 int b = st.top();
                st.pop();
                int a = st.top();
                st.pop();
                st.push(a - b);
            }
            else if(tokens[i] == "*"){
                 int b = st.top();
                st.pop();
                int a = st.top();
                st.pop();
                st.push(a * b);
            }
            else if(tokens[i] == "/"){
                 int b = st.top();
                st.pop();
                int a = st.top();
                st.pop();
                st.push(a / b);
            }
            else {
//                int a = myStringToInt(tokens[i]);
                int a = atoi((tokens[i]).c_str());;
//                cout << tokens[i] << " " << a << endl;
                st.push(a);
            }
        }
        return st.top();

    }
    int myStringToInt(string &s)
    {
        if(s == ""){
            return 0;
        }
        int ret = 1;
        bool IsPositive = false;

//        cout << s << endl;

        if(s[0] == '-'){
            IsPositive = true;
        }
        else{
            ret = ret * (int)(s[0] - '0');
        }
        for(string::size_type i=1 ; i<s.length() ; i++){
            ret *= 10;
            ret += (int)(s[i] - '0');
        }
        if(IsPositive == true){
            return 0 - ret;
        }
        else{
            return ret;
        }
    }
};
int main()
{
    vector<string> tokens;
//    tokens.push_back("2");
//    tokens.push_back("1");
//    tokens.push_back("+");
//    tokens.push_back("3");
//    tokens.push_back("*");
    tokens.push_back("4");
    tokens.push_back("13");
    tokens.push_back("5");
    tokens.push_back("/");
    tokens.push_back("+");
    Solution A;

    cout << A.evalRPN(tokens) << endl;

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值