Maximum Score From Removing Substrings LeetCode solution in C++

1
class Solution {
2
public:
3
int helper(string &str, char a, char b) {
4
int count = 0;
5
stack<char> st;
6
for (int i = 0; i < str.length(); i++) {
7
if (!st.empty() && str[i] == b && st.top() == a) {
8
st.pop();
9
count++;
10
} else {
11
st.push(str[i]);
12
}
13
}
14
str = "";
15
while (!st.empty()) {
16
str += st.top();
17
st.pop();
18
}
19
reverse(str.begin(), str.end());
20
return count;
21
}
22

23
int maximumGain(string s, int x, int y) {
24
int ca = 0, cb = 0;
25
if (x > y) {
26
ca = helper(s, 'a', 'b');
27
cb = helper(s, 'b', 'a');
28
} else {
29
cb = helper(s, 'b', 'a');
30
ca = helper(s, 'a', 'b');
31
}
32
return ca * x + cb * y;
33
}
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0