通过重复将 K 个连续字符转换为 1 来最小化将给定的二进制字符串作为全 1 的操作
给定一个包含 N 个字符的二进制字符串str一个整数K ,任务是找到将字符串的所有字符转换为1所需的最小移动,其中在每次移动时, K个连续字符可以转换为1 。
例子:
Input: str=”0010″, K=3
Output: 2
Explanation:
Move 1: Select the substring from 0 to 2 and replace it with all 1.
Move 2: Select the substring from 1 to 3 and replace it with all 1.
Input: str=”0000010″, K=1
Output: 6
方法:这个问题可以使用贪心方法来解决。要解决此问题,请执行以下步骤:
- 创建一个变量cnt ,以存储所需的最小移动次数。用0初始化它。
- 使用变量i和str[i] = '0'遍历字符串,然后将 i 更新为i + K并将cnt增加1 ,因为无论这些字符是什么,总是需要移动来转换字符str[i ]到'1' 。
- 循环结束后,返回cnt这将是所需的答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find the minimum
// operations required to convert
// the binary string str to all 1s
int minMoves(string str, int K)
{
int N = str.size();
// Variable to store number
// of minimum moves required
int cnt = 0;
int i = 0;
// Loop to traverse str
while (i < N) {
// If element is '0'
if (str[i] == '0') {
i += K;
cnt += 1;
}
// If element is '1'
else {
i++;
}
}
return cnt;
}
// Driver Code
int main()
{
string str = "0010";
int K = 3;
cout << minMoves(str, K);
}
Java
// Java code for the above approach
class GFG {
// Function to find the minimum
// operations required to convert
// the binary String str to all 1s
static int minMoves(String str, int K) {
int N = str.length();
// Variable to store number
// of minimum moves required
int cnt = 0;
int i = 0;
// Loop to traverse str
while (i < N) {
// If element is '0'
if (str.charAt(i) == '0') {
i += K;
cnt += 1;
}
// If element is '1'
else {
i++;
}
}
return cnt;
}
// Driver Code
public static void main(String args[]) {
String str = "0010";
int K = 3;
System.out.println(minMoves(str, K));
}
}
// This code is contributed by Saurabh Jaiswal
Python3
# Python code for the above approach
# Function to find the minimum
# operations required to convert
# the binary string str to all 1s
def minMoves(str, K):
N = len(str)
# Variable to store number
# of minimum moves required
cnt = 0
i = 0
# Loop to traverse str
while (i < N):
# If element is '0'
if (str[i] == '0'):
i += K
cnt += 1
# If element is '1'
else:
i += 1
return cnt
# Driver Code
str = "0010"
K = 3
print(minMoves(str, K))
# This code is contributed by Saurabh Jaiswal
C#
// C# code for the above approach
using System;
class GFG
{
// Function to find the minimum
// operations required to convert
// the binary string str to all 1s
static int minMoves(string str, int K)
{
int N = str.Length;
// Variable to store number
// of minimum moves required
int cnt = 0;
int i = 0;
// Loop to traverse str
while (i < N) {
// If element is '0'
if (str[i] == '0') {
i += K;
cnt += 1;
}
// If element is '1'
else {
i++;
}
}
return cnt;
}
// Driver Code
public static void Main()
{
string str = "0010";
int K = 3;
Console.Write(minMoves(str, K));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
2
时间复杂度: O(N)
辅助空间: O(1)