leetcode[150] Evaluate Reverse Polish Notation
2014-12-17 23:25
417 查看
逆波兰表示法,在维基百科here
一不小心就看到了维基上有说用栈处理。然后就用栈处理了。
需要注意的是,操作数前后不要弄错,stoi可以调用。它应该是在stdlib.h的头文件里,不过我在codeblock上试了不行。
如果自己实现stoi的话:
View Code
一不小心就看到了维基上有说用栈处理。然后就用栈处理了。
需要注意的是,操作数前后不要弄错,stoi可以调用。它应该是在stdlib.h的头文件里,不过我在codeblock上试了不行。
class Solution { public: int evalRPN(vector<string> &tokens) { int size = tokens.size(); if (size == 0) return 0; stack<int> sta; for (int i = 0; i < size; i++) { if (isdigit(tokens[i][0]) || tokens[i].size() > 1) sta.push(stoi(tokens[i])); else { int op1 = sta.top(); sta.pop(); int op2 = sta.top(); sta.pop(); switch(tokens[i][0]) { case '+': sta.push(op1 + op2); break; case '-': sta.push(op2 - op1); break; case '*': sta.push(op1 * op2); break; case '/': sta.push(op2 / op1); break; } } } return sta.top(); } };
如果自己实现stoi的话:
int stoi150(string s) { int flag = 1; if (s[0] == '-') { flag = -1; s = s.substr(1); } else if (s[0] == '+') { s = s.substr(1); } int size = s.size(), ans = 0; for (int i = 0; i < size; i++) { ans = 10 * ans + (s[i] - '0'); } return flag * ans; }
View Code
相关文章推荐
- leetcode(150):Evaluate Reverse Polish Notation
- LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium
- LeetCode150 Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation
- [LeetCode]题解(python):150-Evaluate Reverse Polish Notation
- LeetCode150:Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- [leetcode 150] Evaluate Reverse Polish Notation
- leetcode 150: Evaluate Reverse Polish Notation
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- [Leetcode 150, Medium] Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现
- leetcode-150-Evaluate Reverse Polish Notation
- LeetCode - 150 - Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- leetcode[150]Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation