20.9.6 周赛 5509. 避免重复字母的最小删除成本 中等

题目

给你一个字符串 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 中只含有小写英文字母

思路

  1. 找到连续字符串,再根据字符串的索引,去cost数组的这段子数组中寻找最大的元素
  2. 除去最大元素,这段连续字符串中的所有字符都要删除

代码

class Solution {
public:
    int minCost(string s, vector<int>& cost) {
        int res=0;
        
        for(int i=1;i<s.length();i++){
            if(s[i]==s[i-1]){
                int dist=1;
                for(int j=i+1;j<s.length();j++){
                    if(s[j]==s[i])dist++;
                    else break;
                }
                int max=INT_MIN;
                int maxIndex=i-1;
                for(int k=i-1;k<i+dist;k++){
                    if(cost[k]>max){
                        max=cost[k];
                        maxIndex=k;
                    } 
                }
                for(int l=i-1;l<i+dist;l++){
                    if(l!=maxIndex) res+=cost[l];
                }
                i+=dist-1;
            }
        }
        return res;
    }
};
posted @ 2020-09-06 12:16  肥斯大只仔  阅读(175)  评论(0编辑  收藏  举报