evaluate-reverse-polish-notation(逆波兰表示求值)
2016-09-21 22:10
399 查看
//atoi (表示 ascii
to integer)是把字符串转换成整型数:int
atoi(const char *nptr);
//string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for (int i=0; i<tokens.size(); i++){
string s = tokens[i];
if (s=="+" || s=="-" || s=="*" || s=="/"){
if (st.size()<2)
return 0; //表达式不合法
int result = 0;
int s2 = st.top();st.pop();
int s1 = st.top();st.pop();
if (s=="+"){
result = s1 + s2;
}else if(s=="-"){
result = s1 - s2;
}else if (s=="*"){
result = s1 * s2;
}else if (s=="/"){
result = s1 / s2;
}
st.push(result);
}else{
st.push(atoi(s.c_str()));
}
}
return st.top();
}
};
to integer)是把字符串转换成整型数:int
atoi(const char *nptr);
//string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for (int i=0; i<tokens.size(); i++){
string s = tokens[i];
if (s=="+" || s=="-" || s=="*" || s=="/"){
if (st.size()<2)
return 0; //表达式不合法
int result = 0;
int s2 = st.top();st.pop();
int s1 = st.top();st.pop();
if (s=="+"){
result = s1 + s2;
}else if(s=="-"){
result = s1 - s2;
}else if (s=="*"){
result = s1 * s2;
}else if (s=="/"){
result = s1 / s2;
}
st.push(result);
}else{
st.push(atoi(s.c_str()));
}
}
return st.top();
}
};
相关文章推荐
- Leetcode 150 Evaluate Reverse Polish Notation 反向波兰表示法求值
- Leetcode 150 Evaluate Reverse Polish Notation (求值逆波兰表达式)
- 【LeetCode】Evaluate Reverse Polish Notation(逆波兰表达式求值) -(Linkedin) Medium ++
- lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- LeetCode | Evaluate Reverse Polish Notation(逆波兰式求值)
- Evaluate Reverse Polish Notation--逆波兰式求值
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- LeetCode OJ:Evaluate Reverse Polish Notation(逆波兰表示法的计算器)
- Leetcode (10) Evaluate Reverse Polish Notation (计算逆波兰表示法多项式)
- 逆波兰表达式求值(Evaluate Reverse Polish Notation)
- leetcode_题解_Evaluate Reverse Polish Notation逆波兰式
- 【LeetCode-面试算法经典-Java实现】【151-Evaluate Reverse Polish Notation(计算逆波兰式)】
- Evaluate_Reverse_Polish_Notation 表达式求值
- LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium
- Evaluate Reverse Polish Notation(逆波兰式)
- Java实现逆波兰表达式(Evaluate Reverse Polish Notation)
- [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
- EvaluateReversePolishNotation 逆波兰表达式
- 栈&逆波兰150. Evaluate Reverse Polish Notation