【栈】【字符串和int类型转化】Leetcode 150 逆波兰表达式求值
- 解法1 栈
---------------🎈🎈题目链接 Leetcode 150 逆波兰表达式求值 🎈🎈-------------------
解法1 栈
字符串转化为int类型数据:
Integer.parseInt(s)
Long.parseLong(s)
Double.parseDouble(s)
判断字符串相等
s1.equals(s2)
创建栈
Stack<> mystack = new Stack<>();
时间复杂度O(N)
空间复杂度O(N)
class Solution {public int evalRPN(String[] tokens) {Stack<Integer> mystack = new Stack<>();for(int i = 0; i < tokens.length; i++){if(tokens[i].equals("+")){int temp = mystack.pop();mystack.push(mystack.pop() + temp);} else if(tokens[i].equals("-")){int temp = mystack.pop();mystack.push(mystack.pop() - temp);} else if(tokens[i].equals("*")){int temp = mystack.pop();mystack.push(mystack.pop() * temp);} else if(tokens[i].equals("/")){int temp = mystack.pop();mystack.push(mystack.pop() / temp);} else{mystack.push(Integer.parseInt(tokens[i]));}}return mystack.pop();}
}