C++ solution using stack


  • 0
    F

    O(N) solution using stack

    class Solution {
    public:
        int calPoints(vector<string>& ops) {
            if( ops.size()== 0) return 0;
            stack<int> s;
            int sum = 0;
            for(int i = 0; i < ops.size(); i++ ){
                if(ops[i] == "D" && !s.empty()){
                    int num = 2 * s.top();
                    sum += num;
                    s.push(num);
                }else if (ops[i] == "C" && !s.empty() ){
                    sum -= s.top(); s.pop();
                }else if (ops[i] == "+" && !s.empty()){
                    int num = s.top(); 
                    int top = s.top(); s.pop();
                    if( !s.empty()){
                        num += s.top();
                    }
                    s.push(top);
                    s.push(num);
                    sum += num;
                }else{
                    int num = stoi(ops[i]);
                    s.push(num);
                    sum += num;
                }
            }
            return sum;
        }
    };
    

Log in to reply
 

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