Description
Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s.
Return the minimum cost of deletions such that there are no two identical letters next to each other.
Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change.
Example 1:
Input: s = "abaac", cost = [1,2,3,4,5]
Output: 3
Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other).
Example 2:
Input: s = "abc", cost = [1,2,3]
Output: 0
Explanation: You don't need to delete any character because there are no identical letters next to each other.
Example 3:
Input: s = "aabaa", cost = [1,2,3,4,1]
Output: 2
Explanation: Delete the first and the last character, getting the string ("aba").
Constraints:
- s.length == cost.length
- 1 <= s.length, cost.length <= 10^5
- 1 <= cost[i] <= 10^4
- s contains only lowercase English letters.
分析
题目的意思是:给定一个字符串s,和一个代价数组cost。
思路也很直接,保留重复元素里面代价最大的字符,删除剩下的重复字符就行了。
- total记录重复值的代价之和,maxVal记录重复值的代价最大值。这样最终total-maxVal就是删除元素的代价,更新维护res就行了。
代码
class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
n=len(s)
i=0
res=0
while(i<n):
ch=s[i]
total=0
maxVal=0
while(i<n and s[i]==ch):
maxVal=max(maxVal,cost[i])
total+=cost[i]
i+=1
res+=total-maxVal
return res
参考文献
避免重复字母的最小删除成本