You are given a string s
and two integers x
and y
. You can perform two types of operations any number of times.
- Remove substring
"ab"
and gainx
points.- For example, when removing
"ab"
from"cabxbae"
it becomes"cxbae"
.
- For example, when removing
- Remove substring
"ba"
and gainy
points.- For example, when removing
"ba"
from"cabxbae"
it becomes"cabxe"
.
- For example, when removing
Return the maximum points you can gain after applying the above operations on s
.
Example 1:
Input: s = "cdbcbbaaabab", x = 4, y = 5 Output: 19 Explanation: - Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. - Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. - Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19.
Example 2:
Input: s = "aabbaaxybbaabb", x = 5, y = 4 Output: 20
Constraints:
1 <= s.length <= 105
1 <= x, y <= 104
s
consists of lowercase English letters.
思路:对于一个字符串,能消除的'ab'和'ba'的总数是一样的。
比如'XabaXX',要么消掉一个’ab‘,要么消掉一个’ba‘,
再比如’XababX‘要么消掉2个’ab‘,要么消掉一个’ba‘和一个’ab‘,总量都会是2。
但是当然我们会优先选取分高的(称之为 大字符串 吧),假设是'ab',那问题就转化为了:给定一个只有'a'和’b‘组成的字符串,能构造出多少个'ab',以及会剩下多少'ba'。
用stack来求'ab'。
class Solution(object):
def maximumGain(self, s, x, y):
"""
:type s: str
:type x: int
:type y: int
:rtype: int
"""
if x > y:
c1,c2 = 'a','b'
r1,r2 = x,y
else:
c1,c2 = 'b', 'a'
r1,r2 = y,x
# 拆分成只有'a','b'组成的字符串
split_s = []
prev = -1
for i,c in enumerate(s+'c'):
if c not in ('a','b'):
if prev+1 != i:
split_s.append(s[prev+1:i])
prev = i
res = 0
for s in split_s:
valid_c1 = 0 # 能组成合理的 大字符串 有多少个
count_c1 = 0 # c1有多少个
for c in s:
if c == c1:
count_c1 += 1
else:
if count_c1 > 0:
valid_c1 += 1
count_c1 -= 1
valid = min(s.count(c1), s.count(c2))
res += valid_c1*r1 + (valid-valid_c1)*r2
return res