链接网址:https://leetcode.cn/problems/maximum-score-from-removing-substrings/
题目(中等)
给你一个字符串 s 和两个整数 x 和 y 。你可以执行下面两种操作任意次。
删除子字符串 “ab” 并得到 x 分。
比方说,从 “cabxbae” 删除 ab ,得到 “cxbae” 。
删除子字符串"ba" 并得到 y 分。
比方说,从 “cabxbae” 删除 ba ,得到 “cabxe” 。
请返回对 s 字符串执行上面操作若干次能得到的最大得分。
题解
思路和算法
为了得到最大得分,采用贪心策略,有如下的思想。
当 x ≠ y 时,应首先执行得分高的删除操作直到无法继续删除,然后执行得分低的删除操作直到无法继续删除。
当 x = y 时,可以按任意顺序执行两种操作。
因题目中只涉及"ab"两个字符,存在对偶性,可以发现将’a’换成’b’,'b’换成’a’后,相应的得分也会互换。
步骤:
- 判断x和y的大小,如果x<y,交换分值,同时将字符串逆序
- 第一遍遍历,查找"ab"(此时x为高分值):利用栈的特性
- 第二遍遍历,查找"ba"
C++代码
class Solution {
public:
int maximumGain(string s, int x, int y) {
int ans = 0;
// 步骤1
if (x < y) {
swap(x,y);
reverse(s.begin(),s.end());
}
// 步骤2
stack<char> st1;
for (auto c : s) {
if(c != 'b') {
st1.push(c);
} else {
if(!st1.empty() && st1.top() == 'a') {
st1.pop();
ans += x;
} else {
st1.push(c);
}
}
}
// 步骤3
stack<char> st2;
while (!st1.empty()) {
char c = st1.top();
st1.pop();
if (c != 'b') {
st2.push(c);
} else {
if(!st2.empty() && st2.top() =='a') {
st2.pop();
ans += y;
}
}
}
return ans;
}
};