版權聲明:本文為博主原創(chuàng)文章,未經博主允許不得轉載。
難度:中等
要求:
求逆波蘭表達式的值长豁。
在逆波蘭表達法中城舞,其有效的運算符號包括 +, -, *, / 轩触。每個運算對象可以是整數,也可以是另一個逆波蘭計數表達家夺。
樣例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:
棧數據結構的經典運用脱柱,知道了就簡單.
public class Solution {
/*
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<String> stack = new Stack();
int i = 0;
stack.add(tokens[i]);
i++;
int n1 = 0;
int n2 = 0;
while (!stack.isEmpty() && i < tokens.length) {
String s = tokens[i];
switch (s) {
case "+":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n1 + n2));
break;
case "-":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n2 - n1));
break;
case "*":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n1 * n2));
break;
case "/":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n2 / n1));
break;
default:
stack.add(s);
break;
}
i++;
}
String s = stack.pop();
return Integer.parseInt(s);
}
}