Given a string str and the task is to modify the string such that no three consecutive characters are the same. In a single operation, any character can be inserted at any position in the string. Find the minimum number of such operations required.
Examples:
Input : str = “aabbbcc”
Output: 1
Explanation: “aabbdbcc” is the modified string.
Input: str = “geeksforgeeks”
Output: 0
Explanation: There are no same consecutive characters
Approach:
The idea is to insert the character after the second character to minimize the operations.
Follow the steps below to solve the problem:
- Loop over the string and check at ith index if str[i] == str[i + 1] and str[i] == str[i + 2]
- If this condition is true then increment the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getCount(string str, int n)
{
int cnt = 0;
int i = 0;
while (i < n - 2) {
if (str[i] == str[i + 1] && str[i] == str[i + 2]) {
cnt++;
i = i + 2;
}
else
i++;
}
return cnt;
}
int main()
{
string str = "aabbbcc" ;
int n = str.length();
cout << getCount(str, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int getCount( char [] str, int n)
{
int cnt = 0 ;
int i = 0 ;
while (i < n - 2 ) {
if (str[i] == str[i + 1 ]
&& str[i] == str[i + 2 ]) {
cnt++;
i = i + 2 ;
}
else {
i++;
}
}
return cnt;
}
static public void main(String[] arg)
{
String str = "aabbbcc" ;
int n = str.length();
System.out.println(getCount(str.toCharArray(), n));
}
}
|
Python3
def getCount(str1, n):
cnt = 0
i = 0
while (i < n - 2 ):
if (str1[i] = = str1[i + 1 ] and
str1[i] = = str1[i + 2 ]):
cnt + = 1
i = i + 2
else :
i + = 1
return cnt
str1 = "aabbbcc"
n = len (str1)
print (getCount(str1, n))
|
C#
using System;
class GFG {
static int getCount( string str, int n)
{
int cnt = 0;
int i = 0;
while (i < n - 2) {
if (str[i] == str[i + 1]
&& str[i] == str[i + 2]) {
cnt++;
i = i + 2;
}
else {
i++;
}
}
return cnt;
}
static public void Main()
{
string str = "aabbbcc" ;
int n = str.Length;
Console.WriteLine(getCount(str, n));
}
}
|
Javascript
<script>
function getCount(str, n) {
var cnt = 0;
var i = 0;
while (i < n - 2) {
if (str[i] === str[i + 1] && str[i] === str[i + 2]) {
cnt++;
i = i + 2;
}
else {
i++;
}
}
return cnt;
}
var str = "aabbbcc" ;
var n = str.length;
document.write(getCount(str, n));
</script>
|
Time Complexity: O(N), Traversing over the string of size N.
Auxiliary Space: O(1)