Saturday, July 2, 2016

150. Evaluate Reverse Polish Notation

Typical stack solution.

1:  class Solution {  
2:  public:  
3:    int evalRPN(vector<string>& tokens) {  
4:      stack<int> stk;  
5:      int a = 0, b = 0;  
6:      for (int i = 0; i < tokens.size(); i++) {  
7:        if (isOperand(tokens[i])) {  
8:          a = stk.top(); stk.pop();  
9:          b = stk.top(); stk.pop();  
10:          if (tokens[i] == "+") stk.push(b+a);  
11:          else if (tokens[i] == "-") stk.push(b-a);  
12:          else if (tokens[i] == "*") stk.push(b*a);  
13:          else stk.push(b/a);  
14:        } else {  
15:          stk.push(stoi(tokens[i], NULL, 10));  
16:        }  
17:      }  
18:      return stk.top();  
19:    }  
20:    bool isOperand(string s) {  
21:      return s == "+" || s == "-" || s == "*" || s == "/";  
22:    }  
23:  };  

No comments:

Post a Comment