将二进制字符串转换为全 0 或全 1 所需的最少操作
给定一个二进制字符串str ,任务是找到使字符串的所有字符相同所需的最小操作数,即结果字符串包含全 0 或全 1。在单个操作中,任何连续 0 的块都可以转换为相同长度的连续 1 块,反之亦然。
例子:
Input: str = “000111”
Output: 1
In a single operation, either change all 0s to 1s
or change all 1s to 0s.
Input: str = “0011101010”
Output: 3
All the 1s can be converted to 0s in 3 operations.
方法:问题是将所有字符转换为一个字符。现在因为转换整个连续的字符组算作一个步骤。您可以计算由于它们之间存在其他字符而彼此分隔的不同组的数量。现在,步数将只是这两个数字中的最小值。因此,答案将是连续块 0 的计数或连续块 1 的计数中的最小值。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of
// minimum operations required
int minOperations(string str, int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++) {
// Increment count when consecutive
// characters are different
if (str[i] != str[i + 1])
count++;
}
// Answer is rounding off the
// (count / 2) to lower
return (count + 1) / 2;
}
// Driver code
int main()
{
string str = "000111";
int n = str.length();
cout << minOperations(str, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the count of
// minimum operations required
static int minOperations(String str, int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++)
{
// Increment count when consecutive
// characters are different
if (str.charAt(i) != str.charAt(i + 1))
count++;
}
// Answer is rounding off the
// (count / 2) to lower
return (count + 1) / 2;
}
// Driver code
public static void main(String[] args)
{
String str = "000111";
int n = str.length();
System.out.println(minOperations(str, n));
}
}
// This code is contributed by Princi Singh
Python3
# Python3 implementation of the approach
# Function to return the count of
# minimum operations required
def minOperations(str, n):
count = 0
for i in range(n - 1):
# Increment count when consecutive
# characters are different
if (str[i] != str[i + 1]):
count += 1
# Answer is rounding off the
# (count / 2) to lower
return (count + 1) // 2
# Driver code
str = "000111"
n = len(str)
print(minOperations(str, n))
# This code is contributed
# by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of
// minimum operations required
static int minOperations(string str, int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++)
{
// Increment count when consecutive
// characters are different
if (str[(i)] != str[(i + 1)])
count++;
}
// Answer is rounding off the
// (count / 2) to lower
return (count + 1) / 2;
}
// Driver code
public static void Main()
{
string str = "000111";
int n = str.Length;
Console.WriteLine(minOperations(str, n));
}
}
// This code is contributed by Code_Mech
Javascript
输出:
1