Leetcode OJ : Evaluate Reverse Polish Notation Stack C++ solution

 1 #define ADDITION  '+'

 2 #define SUBSTRACTION  '-'

 3 #define MULTIPLICATION  '*'

 4 #define DIVISION  '/'

 5 

 6 

 7 class Solution {

 8 public:

 9     set<char> tokenSet{'+', '-', '*', '/'};

10     stack<int> num;

11     int evalRPN(vector<string> &tokens) {

12         for (auto &token : tokens) {

13             auto iter = tokenSet.find( token[token.size()-1] );

14             if ( iter == tokenSet.end() ) {

15                 num.push( atoi( token.c_str() ) );

16             } else {

17                int right = num.top();

18                num.pop();

19                int left = num.top();

20                num.pop();

21                switch ( *iter )

22                {

23                    case ADDITION :

24                        num.push(left + right);

25                        break;

26                    case SUBSTRACTION:

27                        num.push(left - right);

28                        break;

29                    case MULTIPLICATION:

30                        num.push(left * right);

31                        break;

32                    case DIVISION:

33                        num.push(left / right);

34                        break;

35                    default:

36                        break;

37                }

38             }

39         }

40         int ret = num.top();

41         num.pop();

42         return ret;

43     }

44 };

 

你可能感兴趣的:(LeetCode)