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

该博客讨论了一个算法问题,即如何找到使字符串中任意相邻两个字母不相同的最小删除成本。给出了三个不同的解决方案,包括双指针法,分别在给定的字符串和代价数组上操作,通过比较和删除字符来达到目标。示例展示了如何应用这些方法,并返回了相应的结果。
摘要由CSDN通过智能技术生成

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


package com.loo;

public class MinCost {

    public static void main(String[] args) {
        String str = "abaac";
        int[] cost = new int[] {1 , 2 , 3 , 4 , 5};
        System.out.println(getMinCost(str , cost));
        
        String str2 = "aabaa";
        int[] cost2 = new int[] {1 , 2 , 3 , 4 , 1};
        System.out.println(getMinCost3(str2 , cost2));
    }
    
    public static int getMinCost(String str , int[] cost) {
        int ret = 0;
        if (str == null || str.length()==0) {
            return ret;
        }
        int i = 0;
        int len = str.length();
        while (i<len) {
            int maxValue = 0;
            int sum = 0;
            char ch = str.charAt(i);
            while (i<len && str.charAt(i) == ch) {
                maxValue = Math.max(maxValue, cost[i]);
                sum += cost[i];
                i++;
            }
            // 保留删除成本最高的字母
            ret += sum - maxValue;
        }
        return ret;
    }
    
    public static int getMinCost2(String str , int[] cost) {
        int ret = 0;
        if (str == null || str.length()==0) {
            return ret;
        }
        int length = cost.length;
        for (int i=1;i<length;i++) {
            if (str.charAt(i-1) == str.charAt(i)) {
                ret += Math.min(cost[i-1], cost[i]);
                // 保留删除成本最高的字母
                cost[i] = Math.max(cost[i-1], cost[i]);
            }
        }
        return ret;
    }
    
    // 双指针思路
    public static int getMinCost3(String str , int[] cost) {
        int ret = 0;
        if (str == null || str.length()==0) {
            return ret;
        }
        int i=0,j=1;
        while (j < cost.length) {
            if (str.charAt(i) == str.charAt(j)) {
            // 取最小成本的字母,既是保留删除成本最高的字母
                ret += Math.min(cost[i], cost[j]);
                if (cost[i] < cost[j]) {
                    i = j++;
                } else {
                    j++;
                }
            } else {
                i = j++;
            }
        }
        return ret;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值