Posted on

Description

Submission

class Solution {
public:
    int maximumGain(string s, int x, int y) {
        if(x < y) {
            reverse(s.begin(), s.end());
            swap(x, y);
        }
        
        int n = s.length();
        vector<int> taken(n, 0);
        int ret = 0;
        string t = "";
        for(int i = 0; i < n; ++i) {
            t.push_back(s[i]);
            if(t.size() >= 2 && t.substr(t.size() - 2) == "ab") {
                t.pop_back();
                t.pop_back();
                ret += x;
            }
        }

        string p = "";
        for(int i = 0; i < t.size(); ++i) {
            p.push_back(t[i]);
            if(p.size() >= 2 && p.substr(p.size() - 2) == "ba") {
                p.pop_back();
                p.pop_back();
                ret += y;
            }
        }

        return ret;
    }
};

Submission 210309

class Solution {
public:
    int maximumGain(string s, int x, int y) {
        string s1 = "ab";
        string s2 = "ba";
        if(x < y) {
            swap(s1, s2);
            swap(x, y);
        }
        
        stack<char> stk;
        
        // erase ba
        int ret = 0;
        for(char c: s) {
            if(stk.empty()) {
                stk.push(c);
                continue;
            }
            if(stk.top() == s1[0] && c == s1[1]) {
                stk.pop();
                ret += x;
            } else {
                stk.push(c);
            }
        }
        
        stack<char> stk2;
        while(!stk.empty()) {
            char c = stk.top();
            stk.pop();
            
            if(stk2.empty()) {
                stk2.push(c);
                continue;
            }
            
            if(c == s1[1] && stk2.top() == s1[0]) {
                stk2.pop();
                ret += y;
            } else {
                stk2.push(c);
            }
        }
        
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *