1717. Maximum Score From Removing Substrings

88 篇文章 0 订阅
18 篇文章 0 订阅

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 gain x points.
    • For example, when removing "ab" from "cabxbae" it becomes "cxbae".
  • Remove substring "ba" and gain y points.
    • For example, when removing "ba" from "cabxbae" it becomes "cabxe".

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值