../ Competitive Programming
-rw-r--r--aguang1020 B1 min read

Leet Code Daily 2024-07-12 - Maximum Score From Removing Substrings

Solution

  • Greedy + Stack.

Code

c++
class Solution {
public:
    int maximumGain(string s, int x, int y) {

        vector<pair<int, string>> subStrs = {
            {x, "ab"},
            {y, "ba"},
        };

        if (subStrs[0].first < subStrs[1].first) {
            swap(subStrs[0], subStrs[1]);
        }

        int ret = 0;
        for (const auto& subStr : subStrs) {
            vector<char> stack;
            for (const auto& c : s) {
                if (!stack.empty() && stack.back() == subStr.second[0] &&
                    c == subStr.second[1]) {
                    ret += subStr.first;
                    stack.pop_back();
                    continue;
                }
                stack.push_back(c);
            }
            s = string(stack.begin(), stack.end());
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window