Maximum Score From Removing Substrings LeetCode solution in C++
1class Solution {2public:3int helper(string &str, char a, char b) {4int count = 0;5stack<char> st;6for (int i = 0; i < str.length(); i++) {7if (!st.empty() && str[i] == b && st.top() == a) {8st.pop();9count++;10} else {11st.push(str[i]);12}13}14str = "";15while (!st.empty()) {16str += st.top();17st.pop();18}19reverse(str.begin(), str.end());20return count;21}2223int maximumGain(string s, int x, int y) {24int ca = 0, cb = 0;25if (x > y) {26ca = helper(s, 'a', 'b');27cb = helper(s, 'b', 'a');28} else {29cb = helper(s, 'b', 'a');30ca = helper(s, 'a', 'b');31}32return ca * x + cb * y;33}34};