📌  相关文章
📜  删除二进制字符串的“ 01”或“ 10”以使其不包含“ 01”或“ 10”

📅  最后修改于: 2021-04-26 18:08:24             🧑  作者: Mango

给定一个二进制字符串str,任务是找到字符串中的子串“01”“10”的缺失的数量,使得给定的字符串是从这些子串免费。打印最小数量的删除。

例子:

方法:我们删除“ 01”“ 10” ,并且二进制字符串仅包含字符“ 0”“ 1” 。因此,删除的最小数量将等于“ 0”和“ 1”的最小数量。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count of deletions
// of sub-strings "01" or "10"
int substrDeletion(string str, int len)
{
  
    // To store the count of 0s and 1s
    int count0 = 0, count1 = 0;
  
    for (int i = 0; i < len; i++) {
        if (str[i] == '0')
            count0++;
        else
            count1++;
    }
  
    return min(count0, count1);
}
  
// Driver code
int main()
{
    string str = "010";
    int len = str.length();
    cout << substrDeletion(str, len);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
      
// Function to return the count of deletions
// of sub-strings "01" or "10"
static int substrDeletion(String str, int len)
{
  
    // To store the count of 0s and 1s
    int count0 = 0, count1 = 0;
  
    for (int i = 0; i < len; i++)
    {
        if (str.charAt(i) == '0')
            count0++;
        else
            count1++;
    }
  
    return Math.min(count0, count1);
}
  
// Driver code
public static void main(String[] args)
{
    String str = "010";
    int len = str.length();
    System.out.println(substrDeletion(str, len));
}
}
  
// This code is contributed by Code_Mech.


Python3
# Python3 implementation of the approach 
  
# Function to return the count of 
# deletions of sub-strings "01" or "10" 
def substrDeletion(string, length) :
  
    # To store the count of 0s and 1s 
    count0 = 0;
    count1 = 0; 
  
    for i in range(length) :
        if (string[i] == '0') :
            count0 += 1; 
        else :
            count1 += 1; 
  
    return min(count0, count1); 
  
# Driver code 
if __name__ == "__main__" :
  
    string = "010"; 
    length = len(string); 
      
    print(substrDeletion(string, length)); 
  
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
  
class GFG
{
      
// Function to return the count of deletions
// of sub-strings "01" or "10"
static int substrDeletion(string str, int len)
{
  
    // To store the count of 0s and 1s
    int count0 = 0, count1 = 0;
  
    for (int i = 0; i < len; i++)
    {
        if (str[i] == '0')
            count0++;
        else
            count1++;
    }
  
    return Math.Min(count0, count1);
}
  
// Driver code
public static void Main()
{
    string str = "010";
    int len = str.Length;
    Console.Write(substrDeletion(str, len));
}
}
  
// This code is contributed by Ita_c.


输出:
1