Advertisement
2645. Minimum Additions to Make Valid String
MediumView on LeetCode
Time: O(n)
Space: O(1)
Approach
Greedily advance through 'abc' template; count extra blocks needed at breaks.
2645.cs
C#
// Approach: Greedily advance through 'abc' template; count extra blocks needed at breaks.
// Time: O(n) Space: O(1)
public class Solution
{
public int AddMinimum(string word)
{
char[] letters = new char[] { 'a', 'b', 'c' };
int ans = 0;
int i = 0, n = word.Length;
while (i < n)
{
foreach (char ch in letters)
{
if (i < n && word[i] == ch)
i++;
else
ans++;
}
}
return ans;
}
}Advertisement
Was this solution helpful?