My 16ms C++ solution: a big fan of using vector class


  • 0
    T
    class Solution {
    private:
        bool isOperand(string s)
        {
            char c[1];
            if(s.length() > 1)
                return false;
            else
            {
                strcpy(c, s.c_str());
                if(c[0] == '+')
                    return true;
                else if(c[0] == '-')
                    return true;
                else if(c[0] == '*')
                    return true;
                else if(c[0] == '/')
                    return true;
                else
                    return false;
            }
        }
        
    public:
        int evalRPN(vector<string>& tokens) {
            int n = tokens.size();
            int i;
            int front, end;
            vector<int> stack;
            for(i=0; i<n; i++)
            {
                if(!isOperand(tokens[i]))
                    stack.push_back(atoi(tokens[i].c_str()));
                else
                {
                    end = stack.back();
                    stack.pop_back();
                    front = stack.back();
                    stack.pop_back();
                    if(strcmp(tokens[i].c_str(), "+") == 0)
                        stack.push_back(front+end);
                    else if(strcmp(tokens[i].c_str(), "-") == 0)
                        stack.push_back(front-end);
                    else if(strcmp(tokens[i].c_str(), "*") == 0)
                        stack.push_back(front*end);
                    else if(strcmp(tokens[i].c_str(), "/") == 0)
                        stack.push_back(front/end);
                    else
                        exit(0);
                }
            }
            
            return stack[0];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.