Skip to content

Latest commit

 

History

History

2645

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

 

Example 1:

Input: word = "b"
Output: 2
Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "a" to obtain the valid string "abc".

Example 2:

Input: word = "aaa"
Output: 6
Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc".

Example 3:

Input: word = "abc"
Output: 0
Explanation: word is already valid. No modifications are needed. 

 

Constraints:

  • 1 <= word.length <= 50
  • word consists of letters "a", "b" and "c" only. 

Related Topics:
String, Dynamic Programming, Stack, Greedy

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/minimum-additions-to-make-valid-string
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int addMinimum(string s) {
        int i = 0, N = s.size(), ans = 0;
        while (i < N) {
            int start = i++;
            while (i < N && s[i] > s[i - 1]) ++i;
            ans += 3 - i + start;
        }
        return ans;
    }
};