[LeetCode] Minimum Additions to Make Valid String

2645. Minimum Additions to Make Valid String

Given a string word to which you can insert letters “a”, “b” or “c” anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid.

A string is called valid if it can be formed by concatenating the string “abc” several times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int addMinimum(string word) {
int res = 0, p = 0;
string abc = "abc";
for(auto w : word) {
while(abc[p] != w) {
res += 1;
p = (p + 1) % 3;
}
p = (p + 1) % 3;
}
while(p != 0) {
res += 1;
p = (p + 1) % 3;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/16/PS/LeetCode/minimum-additions-to-make-valid-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.