连续字符的最小翻转以使字符串中的所有字符相同
给定一个仅由 1 和 0 组成的字符串。我们可以一次性更改此字符串的任何连续序列。找到这个最小翻转次数,使字符串只包含相同的字符。
例子:
Input : 00011110001110
Output : 2
We need to convert 1's sequence
so string consist of all 0's.
Input : 010101100011
Output : 4
我们需要找到字符串中的最小翻转,以便所有字符都相等。我们只需要找到仅由 0 或 1 组成的序列数。然后所需的翻转次数将是这个数字的一半,因为我们可以更改全 0 或全 1。
C++
// CPP program to find min flips in binary
// string to make all characters equal
#include
using namespace std;
// To find min number of flips in binary string
int findFlips(char str[], int n)
{
char last = ' '; int res = 0;
for (int i = 0; i < n; i++) {
// If last character is not equal
// to str[i] increase res
if (last != str[i])
res++;
last = str[i];
}
// To return min flips
return res / 2;
}
// Driver program to check findFlips()
int main()
{
char str[] = "00011110001110";
int n = strlen(str);
cout << findFlips(str, n);
return 0;
}
Java
// Java program to find min flips in binary
// string to make all characters equal
public class minFlips {
// To find min number of flips in binary string
static int findFlips(String str, int n)
{
char last = ' '; int res = 0;
for (int i = 0; i < n; i++) {
// If last character is not equal
// to str[i] increase res
if (last != str.charAt(i))
res++;
last = str.charAt(i);
}
// To return min flips
return res / 2;
}
// Driver program to check findFlips()
public static void main(String[] args)
{
String str = "00011110001110";
int n = str.length();
System.out.println(findFlips(str, n));
}
}
Python 3
# Python 3 program to find min flips in
# binary string to make all characters equal
# To find min number of flips in
# binary string
def findFlips(str, n):
last = ' '
res = 0
for i in range( n) :
# If last character is not equal
# to str[i] increase res
if (last != str[i]):
res += 1
last = str[i]
# To return min flips
return res // 2
# Driver Code
if __name__ == "__main__":
str = "00011110001110"
n = len(str)
print(findFlips(str, n))
# This code is contributed by ita_c
C#
// C# program to find min flips in
// binary string to make all
// characters equal
using System;
public class GFG {
// To find min number of flips
// in binary string
static int findFlips(String str, int n)
{
char last = ' '; int res = 0;
for (int i = 0; i < n; i++) {
// If last character is not
// equal to str[i] increase
// res
if (last != str[i])
res++;
last = str[i];
}
// To return min flips
return res / 2;
}
// Driver program to check findFlips()
public static void Main()
{
String str = "00011110001110";
int n = str.Length;
Console.Write(findFlips(str, n));
}
}
// This code is contributed by nitin mittal
PHP
Javascript
时间复杂度: O(n)
辅助空间: O(1)
输出:
2