题目:
思路:
代码:用switch可以简洁一点
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
int len = tokens.length;
int num1,num2;
for(int i = 0;i < len;i++){
if(tokens[i].length() == 1 &&(tokens[i].charAt(0) == '+' || tokens[i].charAt(0) == '-' || tokens[i].charAt(0) == '*' || tokens[i].charAt(0) == '/')){
num2 = stack.pop();
num1 = stack.pop();
if(tokens[i].charAt(0) == '+'){
int ans = num1 + num2;
stack.push(ans);
continue;
}
if(tokens[i].charAt(0) == '-'){
int ans = num1 - num2;
stack.push(ans);
continue;
}
if(tokens[i].charAt(0) == '*'){
int ans = num1 * num2;
stack.push(ans);
continue;
}
if(tokens[i].charAt(0) == '/'){
int ans = num1 / num2;
stack.push(ans);
continue;
}
}
else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)
Tips:
①字符串转为数字:int num = Integer.parseInt(string)