Evaluate Reverse Polish Notation(逆波兰式)
2014-11-09 20:15
302 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are
Some examples:
主要是题目所给的是字符串的数组,需要多次进行数字到字符串或者字符串到数字的转换,具体实现参考我的blog,整数转字符串,字符串转整数。
这里我采用的是c++标准库sstream来实现转换。
代码:
Valid operators are
+,
-,
*,
/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 逆波兰式,不用说,肯定考虑栈。
主要是题目所给的是字符串的数组,需要多次进行数字到字符串或者字符串到数字的转换,具体实现参考我的blog,整数转字符串,字符串转整数。
这里我采用的是c++标准库sstream来实现转换。
代码:
class Solution { private: bool isSymbol(string a){ return a=="+"||a=="-"||a=="*"||a=="/"; } int Evaluate(int a,int b,char c){ switch (c) { case '+': return a+b; break; case '-': return a-b; break; case '*': return a*b; break; case '/': return a/b; break; default: break; } } public: int evalRPN(vector<string> &tokens) { stack<string> container; for(int i=0;i<tokens.size();++i){ if(isSymbol(tokens[i])&&!container.empty()){ string temp2Str=container.top();container.pop(); string temp1Str=container.top();container.pop(); int temp2; int temp1; stringstream s; s<<temp2Str;s>>temp2; s.clear(); s<<temp1Str;s>>temp1; s.clear(); stringstream s2; int res=Evaluate(temp1,temp2,tokens[i][0]); s2<<res; string resStr=s2.str(); container.push(resStr); }else{ container.push(tokens[i]); } } stringstream s; int result=0; string reultStr=container.top(); s<<reultStr; s>>result; return result; } };
相关文章推荐
- 栈&逆波兰150. Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation(逆波兰表达式求值) -(Linkedin) Medium ++
- LeetCode—Evaluate Reverse Polish Notation 逆波兰写法的解析
- LeetCode-Evaluate Reverse Polish Notation-逆波兰式-栈的应用
- 【LeetCode-面试算法经典-Java实现】【150-Evaluate Reverse Polish Notation(计算逆波兰式)】
- 计算逆波兰式 Evaluate Reverse Polish Notation
- LeetCode OJ 之 Evaluate Reverse Polish Notation (求逆波兰表达式的值)
- 【LeetCode-面试算法经典-Java实现】【151-Evaluate Reverse Polish Notation(计算逆波兰式)】
- leetcode Evaluate Reverse Polish Notation(计算逆波兰表达式)
- Leetcode 150 Evaluate Reverse Polish Notation (求值逆波兰表达式)
- Java Evaluate Reverse Polish Notation(逆波兰表达式)
- leetcode_2 Evaluate Reverse Polish Notation 逆波兰表达式
- 150. Evaluate Reverse Polish Notation(逆波兰式)
- EvaluateReversePolishNotation 逆波兰表达式
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- leetcode_题解_Evaluate Reverse Polish Notation逆波兰式
- Leetcode 150 Evaluate Reverse Polish Notation 反向波兰表示法求值
- evaluate-reverse-polish-notation(逆波兰表示求值)
- Java实现逆波兰表达式(Evaluate Reverse Polish Notation)
- Leetcode刷题记——150. Evaluate Reverse Polish Notation(计算逆波兰表达式)