20.9.6 周賽 5509. 避免重複字母的最小刪除成本 中等
阿新 • • 發佈:2020-09-06
題目
給你一個字串 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 中只含有小寫英文字母
思路
- 找到連續字串,再根據字串的索引,去cost陣列的這段子陣列中尋找最大的元素
- 除去最大元素,這段連續字串中的所有字元都要刪除
程式碼
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; } };