题解 | 牛牛与后缀表达式

牛牛与后缀表达式

https://www.nowcoder.com/practice/a1a4f178f6ff4188890e51da1cc8ce10

#include <cmath>
#include <stack>
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 给定一个后缀表达式,返回它的结果
     * @param str string字符串
     * @return long长整型
     */
    long long legalExp(string str) {
        // write code here
        stack<long long> zhan;
        vector<char> shuzu;
        long long shu = 0;
        for (char c : str) {
            if (c != '#' && c != '+' && c != '-' && c != '*') {
                shuzu.push_back(c);
                continue;
            }
            if (c == '#') {
                for (int i = 0; i < shuzu.size(); i++) {
                    shu = shu * 10 + (shuzu[i] - '0');
                }
                zhan.push(shu);
                shuzu.clear();
                shu = 0;
                continue;;
            }
            if (c == '+' || c == '-' || c == '*') {
                if (zhan.size() < 2) continue;;

                long long houshu = zhan.top();
                zhan.pop();
                long long qianshu = zhan.top();
                zhan.pop();

                long long jieguo;
                switch (c) {
                    case '+': jieguo = qianshu + houshu; break;
                    case '-': jieguo = qianshu - houshu; break;
                    case '*': jieguo = qianshu * houshu; break;
                }

                zhan.push(jieguo);
            }
        }
        if (zhan.empty()) {
            return 0;
        }
        return zhan.top();
    }
};

全部评论

相关推荐

Rac000n:淘天-客户运营部-AI研发工程师,智能客服方向,暑期实习招聘,欢迎联系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务