Minimum number of deletions so that no two consecutive are same
Last Updated :
09 Mar, 2023
Given a string, find minimum number of deletions required so that there will be no two consecutive repeating characters in the string.
Examples:
Input : AAABBB
Output : 4
Explanation : New string should be AB
Input : ABABABAB
Output : 0
Explanation : There are no consecutive repeating characters.
If there are n consecutive same characters delete n-1 out of those n characters.
Algorithm:
- Define a function countDeletions that takes a string str as input and returns an integer.
- Initialize a variable ans to 0.
- Iterate over the string str from the first character till the second last character:
a. If the current character and the next character are the same, increment ans by 1.
- Return ans as the minimum number of deletions required.
Pseudocode:
function countDeletions(str):
ans = 0
for i from 0 to length(str)-2:
if str[i] == str[i+1]:
ans++
return ans
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int countDeletions(string str)
{
int ans = 0;
for ( int i = 0; i < str.length() - 1; i++)
if (str[i] == str[i + 1])
ans++;
return ans;
}
int main()
{
string str = "AAABBB" ;
cout << countDeletions(str);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int countDeletions(String s)
{
int ans = 0 ;
char [] str = s.toCharArray();
for ( int i = 0 ; i < str.length - 1 ; i++)
if (str[i] == str[i + 1 ])
ans++;
return ans;
}
public static void main(String[] args)
{
String str = "AAABBB" ;
System.out.println(countDeletions(str));
}
}
|
Python3
def countDeletions(string):
ans = 0
for i in range ( len (string) - 1 ):
if (string[i] = = string[i + 1 ]):
ans + = 1
return ans
string = "AAABBB"
print (countDeletions(string))
|
C#
using System;
class GFG
{
static int countDeletions(String s)
{
int ans = 0;
char []str = s.ToCharArray();
for ( int i = 0; i < str.Length - 1; i++)
if (str[i] == str[i + 1])
ans++;
return ans;
}
public static void Main()
{
String str = "AAABBB" ;
Console.Write(countDeletions(str));
}
}
|
PHP
<?php
function countDeletions( $str )
{
$ans = 0;
for ( $i = 0; $i < strlen ( $str ) - 1; $i ++)
if ( $str [ $i ] == $str [ $i + 1])
$ans ++;
return $ans ;
}
$str = "AAABBB" ;
echo countDeletions( $str );
?>
|
Javascript
<script>
function countDeletions(s) {
var ans = 0;
var str = s;
for ( var i = 0; i < str.length - 1; i++)
if (str[i] == str[i + 1])
ans++;
return ans;
}
var str = "AAABBB" ;
document.write(countDeletions(str));
</script>
|
Share your thoughts in the comments
Please Login to comment...