LeetCode每日一题(1717. Maximum Score From Removing Substrings)

给定一个字符串s和两个整数x、y,可以进行两种类型的字符串移除操作以获得积分。优先考虑当x小于y时移除'ba',反之移除'ab'。通过策略性地移除子串,求最大可能的积分总和。例如,在给定输入's'和'x'、'y'的情况下,可以通过一系列操作得到最大积分19。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

假如 x < y, 那我们就优先消耗’ba’, 如果 x > y 则我们优先消耗’ab’。 其实我们需要考虑的就以下四中情况, ‘abab’, ‘baba’, ‘bbaa’, ‘aabb’


impl Solution {
    pub fn maximum_gain(s: String, x: i32, y: i32) -> i32 {
        let mut stack: Vec<char> = Vec::new();
        let mut ans = 0;
        for c in s.chars() {
            if stack.is_empty() {
                stack.push(c);
                continue;
            }
            if c == if x <= y { 'a' } else { 'b' } {
                let last = stack.pop().unwrap();
                if last == if x <= y { 'b' } else { 'a' } {
                    ans += if x <= y { y } else { x };
                    continue;
                }
                stack.push(last);
                stack.push(c);
                continue;
            }
            stack.push(c);
        }
        let mut stack2 = Vec::new();
        for c in stack {
            if stack2.is_empty() {
                stack2.push(c);
                continue;
            }
            let last = stack2.pop().unwrap();
            if c == 'a' && last == 'b' {
                ans += y;
                continue;
            }
            if c == 'b' && last == 'a' {
                ans += x;
                continue;
            }
            stack2.push(last);
            stack2.push(c);
        }
        ans
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值