150. Evaluate Reverse Polish Notation

题目

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
Subscribe to see which companies asked this question.


思路

用栈的出入来模拟后缀表达式的计算,注意入参合法性,除法时除数不能为0等场景


代码

class Solution {
public:

    bool isOperatorAndLegal(stack<int> &calStack,string &inputString)
    {
        if(calStack.size() < 2)
        {
            return false;
        }

        //长度不满足运算符要求
        if(inputString.size() != 1)
        {
            return false;
        }
        //不是合法运算符
        char operatorChar = inputString.at(0);
        if(operatorChar != '+'
        && operatorChar != '-'
        && operatorChar != '*'
        && operatorChar != '/')
        {
            return false;
        }
        //除法的时候除数不能为0
        if(operatorChar == '/' && calStack.top() == 0)
        {
            return false;
        }
        return true;
    }

    int getOperatorRslt(int firstNum,int secondNum,char operatorChar)
    {
        switch(operatorChar)
        {
            case '+':
                return firstNum + secondNum;
            case '-':
                return firstNum - secondNum;
            case '*':
                return firstNum * secondNum;
            case '/':
                return firstNum / secondNum;
            default:
                cout<<"getOperatorRslt,inputPara wrong,firstNum = "<<firstNum<<",secondNum = "<<secondNum
                    <<",operatorChar = "<<operatorChar<<endl;
                return 0;
        }
    }

    int evalRPN(vector<string>& tokens) {
        //后缀表达式的计算,用栈
        size_t length = tokens.size();
        if(length == 0)
        {
            return 0;
        }
        if(length == 1)
        {
            return stoi(tokens[0]);
        }

        stack<int> calStack;
        int tempNum;
        int firstNum;
        int secondNum;
        char operatorChar;
        for(size_t i = 0;i < length;i++)
        {
            //也可以用C++11的stoi
            tempNum = atoi(tokens[i].c_str());
            //字符串是0进栈,0的场景前提不包括多个0
            if(tokens[i].size() == 1 && tokens[i].at(0) == '0')
            {
                calStack.push(0);
                continue;
            }
            //是数字就进栈
            if(tempNum != 0)
            {
                calStack.push(tempNum);
                continue;
            }

            //是+,-,*,/且满足当前栈要求
            if(isOperatorAndLegal(calStack,tokens[i]))
            {
                operatorChar = tokens[i].at(0);
                secondNum = calStack.top();
                calStack.pop();
                firstNum = calStack.top();
                calStack.pop();

                calStack.push(getOperatorRslt(firstNum,secondNum,operatorChar));
            }
            else
            {
                return 0;
            }
        }

        //最后要判断当前栈是否只有一个元素
        if(calStack.size() == 1)
        {
            return calStack.top();
        }
        else
        {
            return 0;
        }
    }
};
好的,以下是代码实现: ```c #include <stdio.h> #include <stdlib.h> #include <ctype.h> typedef struct ExpressionTree { int element; struct ExpressionTree* left_tree; struct ExpressionTree* right_tree; } ExpressionTree, *ExpressionTreeRoot; int evaluate(ExpressionTreeRoot T) { if (T->left_tree == NULL && T->right_tree == NULL) { return T->element; } else { int left_value = evaluate(T->left_tree); int right_value = evaluate(T->right_tree); switch (T->element) { case '+': return left_value + right_value; case '-': return left_value - right_value; case '*': return left_value * right_value; case '/': return left_value / right_value; default: return 0; } } } void in_fix(ExpressionTreeRoot T, bool is_root) { if (T == NULL) return; if (T->left_tree != NULL) { if (!is_root && is_leaf(T->left_tree)) { printf("("); } in_fix(T->left_tree, false); } printf("%c", T->element); if (T->right_tree != NULL) { in_fix(T->right_tree, false); if (!is_root && is_leaf(T->right_tree)) { printf(")"); } } } void reverse_polish(ExpressionTreeRoot T) { if (T == NULL) return; reverse_polish(T->left_tree); reverse_polish(T->right_tree); printf("%c", T->element); } bool is_leaf(ExpressionTreeRoot T) { return T->left_tree == NULL && T->right_tree == NULL; } int main() { ExpressionTreeRoot root = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->element = '+'; root->left_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->left_tree->element = '*'; root->right_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->right_tree->element = '-'; root->left_tree->left_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->left_tree->left_tree->element = 3; root->left_tree->right_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->left_tree->right_tree->element = 4; root->right_tree->left_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->right_tree->left_tree->element = 5; root->right_tree->right_tree = (ExpressionTree*)malloc(sizeof(ExpressionTree)); root->right_tree->right_tree->element = 2; printf("Infix expression: "); in_fix(root, true); printf("\n"); printf("Reverse Polish notation: "); reverse_polish(root); printf("\n"); printf("Result: %d\n", evaluate(root)); return 0; } ``` 这个程序将建立一个如下所示的表达式树: ``` + / \ * - / \ / \ 3 4 5 2 ``` 并且提供了三个操作: - `in_fix`:以中缀方式输出表达式 - `reverse_polish`:以后缀方式输出表达式 - `evaluate`:计算整个表达式树的结果 你可以根据需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值