给一个字符串 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;
}
}