LeetCode 5509. 避免重复字母的最小删除成本

文章目录

1. 题目

给你一个字符串 s 和一个整数数组 cost ,其中 cost[i] 是从 s 中删除字符 i 的代价。

返回使字符串任意相邻两个字母不相同最小删除成本

请注意,删除一个字符后,删除其他字符的成本不会改变。

示例 1:
输入:s = "abaac", cost = [1,2,3,4,5]
输出:3
解释:删除字母 "a" 的成本为 3,然后得到 "abac"(字符串中相邻两个字母不相同)。

示例 2:
输入:s = "abc", cost = [1,2,3]
输出:0
解释:无需删除任何字母,因为字符串中不存在相邻两个字母相同的情况。

示例 3:
输入:s = "aabaa", cost = [1,2,3,4,1]
输出:2
解释:删除第一个和最后一个字母,得到字符串 ("aba") 。
 
提示:
s.length == cost.length
1 <= s.length, cost.length <= 10^5
1 <= cost[i] <= 10^4
s 中只含有小写英文字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-deletion-cost-to-avoid-repeating-letters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 相同的连续字符,留下最大花费的
class Solution {
public:
    int minCost(string s, vector<int>& cost) {
    	int sum = 0, temp = cost[0], MAX = cost[0];
    	s += '*';//方便代码处理最后一个位置
        cost.push_back(0);//方便代码处理
    	for(int i = 1; i < s.size(); i++) 
    	{
    		if(s[i] == s[i-1])//跟前面一样,要删除
    		{
    			temp += cost[i];//记录要删除的和
    			MAX = max(MAX, cost[i]);//最后留下最大花费的
			}	
			else
			{
				sum += temp-MAX;//留下最大花费的
				temp = cost[i];//重置
				MAX = cost[i];//重置
			}
    	}
    	return sum;
    }
};

408 ms 97.1 MB


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/108430423