-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path2645-minimum-additions-to-make-valid-string.js
More file actions
49 lines (46 loc) · 1.19 KB
/
2645-minimum-additions-to-make-valid-string.js
File metadata and controls
49 lines (46 loc) · 1.19 KB
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
/**
* 2645. Minimum Additions to Make Valid String
* https://leetcode.com/problems/minimum-additions-to-make-valid-string/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {string} word
* @return {number}
*/
var addMinimum = function(word) {
let result = 0;
let index = 0;
while (index < word.length) {
if (word[index] === 'a') {
if (word[index + 1] === 'b' && word[index + 2] === 'c') {
index += 3;
} else if (word[index + 1] === 'b') {
result += 1;
index += 2;
} else if (word[index + 1] === 'c') {
result += 1;
index += 2;
} else {
result += 2;
index += 1;
}
} else if (word[index] === 'b') {
if (word[index + 1] === 'c') {
result += 1;
index += 2;
} else {
result += 2;
index += 1;
}
} else {
result += 2;
index += 1;
}
}
return result;
};