總結:
- "+".equals("+") 為正確, string不能用== 比較
思路: 用stack 從左到右掃, 如遇到數字則壓棧, 如遇到符號則取出面頭2個數字壓計算, 第一個取出的數字為右邊, 第二個取出的為左邊
class Solution {
public int evalRPN(String[] tokens) {
//思路: 用stack 從左到右掃, 如遇到數字則壓棧, 如遇到符號則取出面頭2個數字壓計算, 第一個取出的數字為右邊, 第二個取出的為左邊
Stack<Integer> stack = new Stack<>();
for (int i=0; i<tokens.length; i++){
if (tokens[i].equals("+")){
stack.push(stack.pop()+stack.pop());
}
else if (tokens[i].equals("-")){
int first =stack.pop();
int second = stack.pop();
stack.push(second - first);
}
else if (tokens[i].equals("*")){
stack.push(stack.pop()*stack.pop());
}
else if (tokens[i].equals("/")){
int first =stack.pop();
int second = stack.pop();
stack.push(second / first);
}
else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}