(LeetCode 面试经典 150 题) 150. 逆波兰表达式求值 (栈)
题目:150. 逆波兰表达式求值
思路:栈,时间复杂度0(n)。
C++版本:
class Solution {
public:int evalRPN(vector<string>& tokens) {stack<int> st;for(auto x:tokens){if(x=="+"){int b=st.top();st.pop();int a=st.top();st.pop();st.push(a+b);}else if(x=="-"){int b=st.top();st.pop();int a=st.top();st.pop();st.push(a-b);}else if(x=="*"){int b=st.top();st.pop();int a=st.top();st.pop();st.push(a*b);}else if(x=="/"){int b=st.top();st.pop();int a=st.top();st.pop();st.push(a/b);}else{int flag=1;int i=0;if(x[0]=='-'){flag=-1;i=1;}int t=0;for(;i<x.size();i++){t=t*10+x[i]-'0';}st.push(t*flag);}}return st.top();}
};
JAVA版本:
class Solution {public int evalRPN(String[] tokens) {Deque<Integer> st=new ArrayDeque<>();for(var x:tokens){if(x.equals("+")){int b=st.pop();int a=st.pop();st.push(a+b);}else if(x.equals("-")){int b=st.pop();int a=st.pop();st.push(a-b);}else if(x.equals("*")){int b=st.pop();int a=st.pop();st.push(a*b);}else if(x.equals("/")){int b=st.pop();int a=st.pop();st.push(a/b);}else{int flag=1;int i=0;if(x.charAt(0)=='-'){flag=-1;i=1;}int t=0;for(;i<x.length();i++){t=t*10+x.charAt(i)-'0';}st.push(t*flag);}}return st.pop();}
}
GO版本:
func evalRPN(tokens []string) int {st:=[]int{}for _,x:=range tokens {if x=="+" {a,b:=st[len(st)-2],st[len(st)-1]st=st[:len(st)-2]st=append(st,a+b)}else if x=="-" {a,b:=st[len(st)-2],st[len(st)-1]st=st[:len(st)-2]st=append(st,a-b)}else if x=="*" {a,b:=st[len(st)-2],st[len(st)-1]st=st[:len(st)-2]st=append(st,a*b)}else if x=="/" {a,b:=st[len(st)-2],st[len(st)-1]st=st[:len(st)-2]st=append(st,a/b)}else{flag,i:=1,0if x[0]=='-' {flag=-1i=1}t:=0for ;i<len(x);i++ {t=t*10+int(x[i]-'0')}st=append(st,flag*t)}}return st[0]
}