📌  相关文章
📜  最小删除数,使得没有两个连续的相同

📅  最后修改于: 2022-05-13 01:57:07.209000             🧑  作者: Mango

最小删除数,使得没有两个连续的相同

给定一个字符串,找出所需的最小删除次数,这样字符串中就不会出现两个连续的重复字符。
例子:

Input : AAABBB
Output : 4
Explanation : New string should be AB

Input : ABABABAB
Output : 0
Explanation : There are no consecutive repeating characters.

如果有 n 个连续的相同字符,则从这 n 个字符中删除 n-1 个。

C++
// CPP code to count minimum deletions required
// so that there are no consecutive characters left
#include 
using namespace std;
 
int countDeletions(string str)
{
    int ans = 0;
    for (int i = 0; i < str.length() - 1; i++)
        
        // If two consecutive characters are
        // the same, delete one of them.
        if (str[i] == str[i + 1])
            ans++;
         
   return ans;
}
 
// Driver code
int main()
{
    string str = "AAABBB";
 
    // Function call to print answer
    cout << countDeletions(str);
 
    return 0;
}


Java
// Java code to count minimum deletions required
// so that there are no consecutive characters left
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 two consecutive characters are
        // the same, delete one of them.
        if (str[i] == str[i + 1])
            ans++;           
       
        return ans;
  }
 
    // Driver code
    public static void main(String[] args)
    {
      String str = "AAABBB";
      // Function call to print answer
     System.out.println(countDeletions(str));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */


Python3
# Python code to count minimum deletions required
# so that there are no consecutive characters left\
 
def countDeletions(string):
    ans = 0
    for i in range(len(string) - 1):
         
        # If two consecutive characters are
        # the same, delete one of them.
        if (string[i] == string[i + 1]):
            ans += 1
         
    return ans
  
# Driver code
string = "AAABBB"
 
# Function call to print answer
print(countDeletions(string))
 
# This code is contributed by Sachin Bisht


C#
// C# Program to count minimum deletions
// required so that there are no
// consecutive characters left
using System;
 
class GFG
{
     
// Function for counting deletions   
static int countDeletions(String s)
{
    int ans = 0;
    char []str = s.ToCharArray();
 
    for (int i = 0; i < str.Length - 1; i++)
         
        // If two consecutive characters are
        // the same, delete one of them.
        if (str[i] == str[i + 1])
            ans++;        
     
        return ans;
}
 
    // Driver code
    public static void Main()
    {
        String str = "AAABBB";
     
        // Function call to print answer
        Console.Write(countDeletions(str));
    }
}
 
// This code is contributed by Nitin Mittal.


PHP


Javascript


输出:

4