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 thatword becomes valid.
A string is called valid if it can be formed by concatenating the string “abc” several times.
Input: word ="b"Output: 2Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "b" to obtain the valid string "**a** b**c** ".
A valid string must be made up of repeating “abc” patterns. To make the string valid, we need to insert the minimum number of characters so that every substring of length 3 forms “abc”. We can process the string in chunks of 3 and count the missing characters for each chunk.
classSolution {
publicintaddMinimum(String word) {
int ans = 0;
for (int i = 0; i < word.length(); i += 3) {
String pat ="abc";
for (int j = 0; j < 3; ++j) {
if (i + j >= word.length() || word.charAt(i + j) != pat.charAt(j)) ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
defadd_minimum(word: str) -> int:
ans =0 pat ="abc" n = len(word)
i =0while i < n:
for j in range(3):
if i + j >= n or word[i + j] != pat[j]:
ans +=1 i +=3return ans