[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式

[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式,第1张

概述Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers sho

Evaluate the value of an arithmetic Expression in Reverse Polish Notation.

ValID operators are +-*/. Each operand may be an integer or another Expression.

Note:

division between two integers should truncate toward zero. The given rpn Expression is always valID. That means the Expression would always evaluate to a result and there won‘t be any divIDe by zero operation.

Example 1:

input: ["2","1","+","3","*"]Output: 9Explanation: ((2 + 1) * 3) = 9

Example 2:

input: ["4","13","5","/","+"]Output: 6Explanation: (4 + (13 / 5)) = 6

Example 3:

input: ["10","6","9","-11","*","17","+"]Output: 22Explanation:   ((10 * (6 / ((9 + 3) * -11))) + 17) + 5= ((10 * (6 / (12 * -11))) + 17) + 5= ((10 * (6 / -132)) + 17) + 5= ((10 * 0) + 17) + 5= (0 + 17) + 5= 17 + 5= 22

波兰表达式,所有 *** 作符置于 *** 作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识 *** 作符的优先级。

逆波兰记法中, *** 作符置于 *** 作数的后面。例如表达“三加四”时,写作“3 4 +”,而不是“3 + 4”。如果有多个 *** 作符, *** 作符置于第二个 *** 作数的后面,所以常规中缀记法的“3 - 4 + 5”在逆波兰记法中写作“3 4 - 5 +”:先3减去4,再加上5。使用逆波兰记法的一个好处是不需要使用括号。例如中缀记法中“3 - 4 * 5”与“(3 - 4)*5”不相同,但后缀记法中前者写做“3 4 5 * -”,无歧义地表示“3 (4 5 *) -”;后者写做“3 4 - 5 *”。

逆波兰表达式的解释器一般是基于堆栈的。解释过程一般是: *** 作数入栈;遇到 *** 作符时, *** 作数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。因此逆波兰表达式的求值使用堆栈结构很容易实现,并且能很快求值。

注意:逆波兰记法并不是简单的波兰表达式的反转。因为对于不满足交换律的 *** 作符,它的 *** 作数写法仍然是常规顺序,如,波兰记法“/ 6 3”的逆波兰记法是“6 3 /”而不是“3 6 /”;数字的数位写法也是常规顺序。

解法1: 栈Stack

解法2: 递归

Java:

public class Solution {    public int evalrpn(String[] tokens) {        int a,b;		Stack<Integer> S = new Stack<Integer>();		for (String s : tokens) {			if(s.equals("+")) {				S.add(S.pop()+S.pop());			}			else if(s.equals("/")) {				b = S.pop();				a = S.pop();				S.add(a / b);			}			else if(s.equals("*")) {				S.add(S.pop() * S.pop());			}			else if(s.equals("-")) {				b = S.pop();				a = S.pop();				S.add(a - b);			}			else {				S.add(Integer.parseInt(s));			}		}			return S.pop();	}}

Java:

public int evalrpn(String[] a) {  Stack<Integer> stack = new Stack<Integer>();    for (int i = 0; i < a.length; i++) {    switch (a[i]) {      case "+":        stack.push(stack.pop() + stack.pop());        break;                case "-":        stack.push(-stack.pop() + stack.pop());        break;                case "*":        stack.push(stack.pop() * stack.pop());        break;      case "/":        int n1 = stack.pop(),n2 = stack.pop();        stack.push(n2 / n1);        break;                default:        stack.push(Integer.parseInt(a[i]));    }  }    return stack.pop();}

Python:  

# Time:  O(n)# Space: O(n)import operatorclass Solution:    # @param tokens,a List of string    # @return an integer    def evalrpn(self,tokens):        numerals,operators = [],{"+": operator.add,"-": operator.sub,"*": operator.mul,"/": operator.div}        for token in tokens:            if token not in operators:                numerals.append(int(token))            else:                y,x = numerals.pop(),numerals.pop()                numerals.append(int(operators[token](x * 1.0,y)))        return numerals.pop()if __name__ == "__main__":    print(Solution().evalrpn(["2","*"]))    print(Solution().evalrpn(["4","+"]))    print(Solution().evalrpn(["10","+"]))

C++:

class Solution {public:    int evalrpn(vector<string> &tokens) {        if (tokens.size() == 1) return atoi(tokens[0].c_str());        stack<int> s;        for (int i = 0; i < tokens.size(); ++i) {            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")        {                s.push(atoi(tokens[i].c_str()));            } else {                int m = s.top();                s.pop();                int n = s.top();                s.pop();                if (tokens[i] == "+") s.push(n + m);                if (tokens[i] == "-") s.push(n - m);                if (tokens[i] == "*") s.push(n * m);                if (tokens[i] == "/") s.push(n / m);            }        }        return s.top();    }};

C++:  

class Solution {public:    int evalrpn(vector<string>& tokens) {        int op = tokens.size() - 1;        return helper(tokens,op);    }    int helper(vector<string>& tokens,int& op) {        string s = tokens[op];        if (s == "+" || s == "-" || s == "*" || s == "/") {            int v2 = helper(tokens,--op);            int v1 = helper(tokens,--op);            if (s == "+") return v1 + v2;            else if (s == "-") return v1 - v2;            else if (s == "*") return v1 * v2;            else return v1 / v2;        } else {            return stoi(s);        }    }};
总结

以上是内存溢出为你收集整理的[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式全部内容,希望文章能够帮你解决[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1234652.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存