题目:
分析:
都想到了贪心,先ab或ba,选择分数大的。
奈何只想到了replace,没有想到栈,太菜了。
代码:
class Solution {
public:
int maximumGain(string s, int x, int y) {
stack<int> st;
for(int i=s.size()-1;i>=0;i--)
{
st.push(s[i]);
}
int ans=0;
if(x>y)
{
//先 ab
stack<int> st1;
while(1)
{
if(st.empty()) break;
if(st1.empty())
{
st1.push(st.top());
st.pop();
continue;
}
if(st1.top()=='a'&&st.top()=='b') {
ans+=x;
st1.pop();st.pop();
continue;
}
st1.push(st.top());
st.pop();
}
while(!st1.empty()) {
st.push(st1.top());
st1.pop();
}
//再 ba
stack<int> st2;
while(1)
{
if(st.empty()) break;
if(st2.empty())
{
st2.push(st.top());
st.pop();
continue;
}
if(st2.top()=='b'&&st.top()=='a') {
ans+=y;
st2.pop();st.pop();
continue;
}
st2.push(st.top());
st.pop();
}
}
else{
//先 ab
stack<int> st1;
while(1)
{
if(st.empty()) break;
if(st1.empty())
{
st1.push(st.top());
st.pop();
continue;
}
if(st1.top()=='b'&&st.top()=='a') {
ans+=y;
st1.pop();st.pop();
continue;
}
st1.push(st.top());
st.pop();
}
while(!st1.empty()) {
st.push(st1.top());
st1.pop();
}
//再 ba
stack<int> st2;
while(1)
{
if(st.empty()) break;
if(st2.empty())
{
st2.push(st.top());
st.pop();
continue;
}
if(st2.top()=='a'&&st.top()=='b') {
ans+=x;
st2.pop();st.pop();
continue;
}
st2.push(st.top());
st.pop();
}
}
return ans;
}
};