zoukankan      html  css  js  c++  java
  • LeetCode 150. 逆波兰表达式求值

    题目描述链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

    解题思路:栈的典型应用,并注意减法和除法不满足交换率。

    LeetCode C++求解代码:

    class Solution {
    public:
        stack<string>S;
        int evalRPN(vector<string>& tokens) {
             for(int i=0;i<tokens.size();i++){
                 if(tokens[i]=="+"){
                     string temp1=S.top();
                     S.pop();
                     string temp2=S.top();
                     S.pop();
                     int res=std::stoi(temp1)+std::stoi(temp2);
                     string ans=std::to_string(res);
                     S.push(ans);
                 }
                 else if(tokens[i]=="-"){
                     string temp1=S.top();
                     S.pop();
                     string temp2=S.top();
                     S.pop();
                     int res=std::stoi(temp2)-std::stoi(temp1);
                     string ans=std::to_string(res);
                     S.push(ans);
                 }
                 else if(tokens[i]=="*"){
                    string temp1=S.top();
                     S.pop();
                     string temp2=S.top();
                     S.pop();
                     int res=std::stoi(temp1)*std::stoi(temp2);
                     string ans=std::to_string(res);
                     S.push(ans);
                 }
                 else if(tokens[i]=="/"){
                    string temp1=S.top();
                     S.pop();
                     string temp2=S.top();
                     S.pop();
                     int res=std::stoi(temp2)/std::stoi(temp1);
                     string ans=std::to_string(res);
                     S.push(ans);
                     printf("%d",res);
                 }
                 else{
                     S.push(tokens[i]);
                 }
             }
             return std::stoi(S.top());
    
        }
    };
  • 相关阅读:
    JS对象
    常见简单算法的实现
    JavaScript基础
    CSS3 边框 border-image
    HTTP消息头详解
    apache安装
    常见访问错误整理
    apache虚拟主机配置
    apache配置项
    Windows下使用ssh-add报错 Error connecting to agent: No such file or directory
  • 原文地址:https://www.cnblogs.com/zzw-/p/13586330.html
Copyright © 2011-2022 走看看