|
| 1 | +/* |
| 2 | +Evaluate the value of an arithmetic expression in Reverse Polish Notation. |
| 3 | +
|
| 4 | +Valid operators are +, -, *, /. Each operand may be an integer or another expression. |
| 5 | +
|
| 6 | +Note: |
| 7 | +
|
| 8 | +Division between two integers should truncate toward zero. |
| 9 | +The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. |
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: ["2", "1", "+", "3", "*"] |
| 13 | +Output: 9 |
| 14 | +Explanation: ((2 + 1) * 3) = 9 |
| 15 | +Example 2: |
| 16 | +
|
| 17 | +Input: ["4", "13", "5", "/", "+"] |
| 18 | +Output: 6 |
| 19 | +Explanation: (4 + (13 / 5)) = 6 |
| 20 | +Example 3: |
| 21 | +
|
| 22 | +Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] |
| 23 | +Output: 22 |
| 24 | +Explanation: |
| 25 | + ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 |
| 26 | += ((10 * (6 / (12 * -11))) + 17) + 5 |
| 27 | += ((10 * (6 / -132)) + 17) + 5 |
| 28 | += ((10 * 0) + 17) + 5 |
| 29 | += (0 + 17) + 5 |
| 30 | += 17 + 5 |
| 31 | += 22 |
| 32 | +
|
| 33 | +来源:力扣(LeetCode) |
| 34 | +链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation |
| 35 | +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ |
| 36 | + |
| 37 | +/* O(N) in time and O(N) in space */ |
| 38 | +#include <vector> |
| 39 | +#include <string> |
| 40 | +#include <stack> |
| 41 | +using namespace std; |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + int evalRPN(vector<string>& tokens) { |
| 46 | + stack<int> s; |
| 47 | + |
| 48 | + for(int i=0; i<(int)tokens.size(); ++i){ |
| 49 | + if(tokens[i][0]=='+'){ |
| 50 | + int rhs = s.top(); s.pop(); |
| 51 | + int lhs = s.top(); s.pop(); |
| 52 | + s.push(lhs+rhs); |
| 53 | + } |
| 54 | + else if( (tokens[i].size()==1)&&(tokens[i][0]=='-') ){ |
| 55 | + int rhs = s.top(); s.pop(); |
| 56 | + int lhs = s.top(); s.pop(); |
| 57 | + s.push(lhs-rhs); |
| 58 | + } |
| 59 | + else if(tokens[i][0]=='*'){ |
| 60 | + int rhs = s.top(); s.pop(); |
| 61 | + int lhs = s.top(); s.pop(); |
| 62 | + s.push(lhs*rhs); |
| 63 | + } |
| 64 | + else if(tokens[i][0]=='/'){ |
| 65 | + int rhs = s.top(); s.pop(); |
| 66 | + int lhs = s.top(); s.pop(); |
| 67 | + s.push(lhs/rhs); |
| 68 | + } |
| 69 | + else{ |
| 70 | + int temp = 0; |
| 71 | + bool is_pos = true; |
| 72 | + for(int j=0; j<(int)tokens[i].size(); ++j){ |
| 73 | + if(tokens[i][j]=='-') is_pos = false; |
| 74 | + else{ |
| 75 | + temp = temp*10 + tokens[i][j] - '0'; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + if(is_pos) s.push(temp); |
| 80 | + else s.push(-temp); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return s.top(); |
| 85 | + } |
| 86 | +}; |
0 commit comments