LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium

简介: 题目: Evaluate Reverse Polish Notation Evaluatethe value of an arithmetic expression in Reverse Polish Notation.

题目: Evaluate Reverse Polish Notation

Evaluatethe 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

简单题,借助一个stack就可以实现,将数值入栈,遇操作符时将两个数值出栈,计算后再入栈,如此即可实现。

int evalRPN(vector<string> &tokens)
{
    stack<int> stokens;
    for (int i = 0; i < tokens.size(); ++ i) {
        if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
            int x1 = stokens.top();
            stokens.pop();
            int x2 = stokens.top();
            stokens.pop();
            int x3 = caculate(x1, x2, tokens[i]); //计算之后再入栈
            stokens.push(x3);
        }
        else {
            stokens.push(atoi(tokens[i].c_str()));
        }
    }
    return stokens.top();
}
int caculate(int x1, int x2, string s) 
{
    int result;
    if (s == "+")
        result = x1 + x2;
    else if (s == "-") 
        result = x1 - x2;
    else if (s == "*")
        result = x1 * x2;
    else {
        if (x1 >= x2)
            result = x1 / x2;
        else
            result = x2 / x1;
    }
    return result;
}

 

目录
相关文章
力扣203移除链表元素:思路分析+代码实现+方法总结(伪头节点法&递归)
力扣203移除链表元素:思路分析+代码实现+方法总结(伪头节点法&递归)
277 0
|
存储 算法 数据可视化
力扣155题最全解法:如何实现支持常数时间获取最小值的最小栈(附详细图解和复杂度分析)
力扣155题最全解法:如何实现支持常数时间获取最小值的最小栈(附详细图解和复杂度分析)
|
算法 搜索推荐 Java
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
466 3
|
存储 算法 Java
【经典算法】LeetCode 5: 最长回文子串(Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 5: 最长回文子串(Java/C/Python3实现含注释说明,Medium)
435 2
|
存储 缓存 算法
【经典算法】LeetCode 1143:最长公共子序列Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 1143:最长公共子序列Java/C/Python3实现含注释说明,Medium)
127 1
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点.
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点
213 1
|
存储 算法 数据挖掘
LeetCode 题目 43:字符串相乘 多种算法分析对比 【python】
LeetCode 题目 43:字符串相乘 多种算法分析对比 【python】
|
SQL
leetcode-SQL-550. 游戏玩法分析 IV
leetcode-SQL-550. 游戏玩法分析 IV
122 1
|
SQL
leetcode-SQL-1158. 市场分析 I
leetcode-SQL-1158. 市场分析 I
74 1
|
SQL
leetcode-SQL-1084. 销售分析III
leetcode-SQL-1084. 销售分析III
118 0

热门文章

最新文章