[leetcode] Evaluate Reverse Polish Notation
1900 ワード
Evaluate Reverse Polish Notation
再帰の使用
stackを使用して反復
再帰の使用
class Solution {
public:
bool is_operator(const string &op){
return op.size()==1&&string("+-*/").find(op)!=string::npos;//
}
int evalRPN(vector<string> &tokens) {
int x,y;
auto token=tokens.back();//
tokens.pop_back();
if(is_operator(token)){
y=evalRPN(tokens);//
x=evalRPN(tokens);//
if(token[0]=='+'){
x+=y;
}else if(token[0]=='-'){
x-=y;
}else if(token[0]=='*'){
x*=y;
}else{
x/=y;
}
}else{
//size_t i;
//x=stoi(token,&i);// int
x=atoi(token.c_str());
}
return x;
}
};
stackを使用して反復
class Solution {
public:
bool is_operator(const string &op){
return op.size()==1&&string("+-*/").find(op)!=string::npos;
}
int evalRPN(vector<string> &tokens) {
stack<string> stk;
for(auto token:tokens){
if(!is_operator(token)){
stk.push(token);
}else{
int y=stoi(stk.top());// , string int
stk.pop();
int x=stoi(stk.top());
stk.pop();
if(token[0]=='+'){
x+=y;
}else if(token[0]=='-'){
x-=y;
}else if(token[0]=='*'){
x*=y;
}else{
x/=y;
}
stk.push(to_string(x));//int string,
}
}
return stoi(stk.top());//
}
};