Evaluate Reverse Polish Notation
2014-03-19 11:44
204 查看
some example:
![](https://img-blog.csdn.net/20140319113825468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2FuZ19jaGVuZ19oZWk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
其实就是一个后序遍历求值的问题,利用栈的后进先出的思想,每次遇到一个运算符,进行两次出栈操作,找出对应的两个数字并计算值,然后重新入栈。以前一直以为只要判断字符<'0'或者>'9'就能判断是否是运算符,但是提交失败,原来会存在负数的情况,这点以前没有注意到,还好这里面只有4个运算符.class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> q;
string str1[4]={"*","-","+","/"};
int flag = 0;
for(vector<string>::const_iterator iter = tokens.begin();iter!=tokens.end();iter++){
for(int i=0;i<(sizeof(str1)/sizeof(str1[1]));i++){
if(str1[i]==*iter)
{ flag=1;
break;
}
}
if(flag){
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c;
if((*iter)=="+"){
c = a+b;
}
else if((*iter)=="-"){
c =b-a;
}
else if((*iter)=="*"){
c=a*b;
}
else if((*iter)=="/"){
c = b/a;
}
q.push(c);
flag =0;
}
else
q.push(atoi((*iter).c_str()));
}
int d =q.top();
q.pop();
return d;
}
};
其实就是一个后序遍历求值的问题,利用栈的后进先出的思想,每次遇到一个运算符,进行两次出栈操作,找出对应的两个数字并计算值,然后重新入栈。以前一直以为只要判断字符<'0'或者>'9'就能判断是否是运算符,但是提交失败,原来会存在负数的情况,这点以前没有注意到,还好这里面只有4个运算符.class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> q;
string str1[4]={"*","-","+","/"};
int flag = 0;
for(vector<string>::const_iterator iter = tokens.begin();iter!=tokens.end();iter++){
for(int i=0;i<(sizeof(str1)/sizeof(str1[1]));i++){
if(str1[i]==*iter)
{ flag=1;
break;
}
}
if(flag){
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c;
if((*iter)=="+"){
c = a+b;
}
else if((*iter)=="-"){
c =b-a;
}
else if((*iter)=="*"){
c=a*b;
}
else if((*iter)=="/"){
c = b/a;
}
q.push(c);
flag =0;
}
else
q.push(atoi((*iter).c_str()));
}
int d =q.top();
q.pop();
return d;
}
};
相关文章推荐
- leetcode 150.Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 【Leetcode长征系列】Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- LeetCode—Evaluate Reverse Polish Notation 逆波兰写法的解析
- Evaluate Reverse Polish Notation
- leetcode - [2]Evaluate Reverse Polish Notation
- 【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)
- Evaluate Reverse Polish Notation
- [leetcode] Evaluate Reverse Polish Notation
- 逆波兰表达式求值(Evaluate Reverse Polish Notation)
- leetcode_Evaluate Reverse Polish Notation
- leetcode 150: Evaluate Reverse Polish Notation
- 【LeetCode】之Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值
- (java)Evaluate Reverse Polish Notation
- LeetCode--evaluate-reverse-polish-notation
- 150. Evaluate Reverse Polish Notation