leetcode 1578 - Minimum Deletion Cost to Avoid Repeating Letters

https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
int minCost(string s, vector<int>& cost) {
int i = 0, j = 1;
int size = s.size();

int min_cost = 0;

while (j < size) {
if (s[j] == s[i]) {
if (cost[j] < cost[i]) {
min_cost += cost[j];
} else {
min_cost += cost[i];
i = j;
}
} else {
i = j;
}

j++;
}

return min_cost;
}
};

class Solution01 {
public:
int minCost(string s, vector<int>& cost) {
stack<int> stk;

int total = 0;

for (int i = 0; i < s.size(); i++) {
if (stk.empty())
stk.push(i);
else {
int k = stk.top();
if (s[k] != s[i])
stk.push(i);
else {
if (cost[k] > cost[i])
total += cost[i];
else {
total += cost[k];
stk.pop();
stk.push(i);
}
}
}
}

return total;
}
};