0
点赞
收藏
分享

微信扫一扫

150. Evaluate Reverse Polish Notation

伢赞 2022-08-03 阅读 67


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

class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
String operators = "+-*/";
for(String token : tokens){
if(!operators.contains(token)){
s.push(Integer.valueOf(token));
continue;
}

int a = s.pop();
int b = s.pop();
if(token.equals("+")) {
s.push(b + a);
} else if(token.equals("-")) {
s.push(b - a);
} else if(token.equals("*")) {
s.push(b * a);
} else {
s.push(b / a);
}
}
return s.pop();
}
}

class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();

for (int i = 0; i < tokens.length; i++) {

String str = tokens[i];

if (str.equals("+") || str.equals("*") || str.equals("/") || str.equals("-")) {
int a2 = stack.pop();
int a1 = stack.pop();
if (str.equals("+"))
stack.push(a1 + a2);
else if (str.equals("-"))
stack.push(a1 - a2);
else if (str.equals("*"))
stack.push(a1 * a2);
else if (str.equals("/"))
stack.push(a1 / a2);
} else stack.push(Integer.parseInt(str));

}

return stack.pop();
}
}

class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> intermediateResults = new LinkedList<>();
for(String s : tokens){
if("+-*/".contains(s)){
int y = intermediateResults.removeLast();
int x = intermediateResults.removeLast();
switch(s){
case "+":
intermediateResults.add(x + y); break;
case "-":
intermediateResults.add(x - y); break;
case "*":
intermediateResults.add(x * y); break;
case "/":
intermediateResults.add(x / y); break;
}
} else {
intermediateResults.add(Integer.parseInt(s));
}
}
return intermediateResults.poll();
}
}


举报

相关推荐

0 条评论