Skip to content

2645. Minimum Additions to Make Valid String 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int addMinimum(string word) {
    const string letters = "abc";
    int ans = 0;
    int i = 0;

    while (i < word.length())
      for (const char c : letters) {
        if (i < word.length() && word[i] == c)
          ++i;
        else
          ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int addMinimum(String word) {
    final char[] letters = new char[] {'a', 'b', 'c'};
    int ans = 0;
    int i = 0;

    while (i < word.length())
      for (final char c : letters) {
        if (i < word.length() && word.charAt(i) == c)
          ++i;
        else
          ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def addMinimum(self, word: str) -> int:
    letters = ['a', 'b', 'c']
    ans = 0
    i = 0

    while i < len(word):
      for c in letters:
        if i < len(word) and word[i] == c:
          i += 1
        else:
          ans += 1

    return ans