📌  相关文章
📜  仅将二进制字符串转换为 0 所需的翻转字符的最低成本

📅  最后修改于: 2021-10-26 06:46:46             🧑  作者: Mango

给定二进制字符串str和整数A ,表示将连续的1 s 转换为0 s 的成本,以及B ,表示将0 s 转换为1 s 的成本。任务是找到将字符串str仅减少到0最小成本

例子:

方法:根据以下观察可以解决给定的问题:

请按照以下步骤解决问题:

  • 初始化一个变量left_1并将最左边的 ‘1’的索引存储在str 中
  • 初始化另一个变量right_1并将最右边的 ‘1’的索引存储在str 中
  • 如果left_1right_1不存在,则str已经仅由0组成。因此,打印0作为最小成本
  • 否则, str中至少有一个“1” 。因此,初始化cost = A
  • 用指针i遍历字符串str 中left_1right_1的字符
    • 计算i右侧连续0的数量并将其存储在变量zeroes 中
    • 如果的长度超过0 ,则将0 s 转换为1 s 以获取零 * B的成本,或者将连续的1 s 转换为0 s 以获取A的成本。
    • 因此,将成本增加min(zeroes * B, A)
  • 最后,打印得到的最小成本。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum cost
// to convert given string to 0s only
void convert_to_allzeroes(string str,
                          int a, int b)
{
    // Length of string
    int len = str.length();
 
    // Stores the index of leftmost '1' in str
    int left_1, i = 0;
 
    while (i < len && str[i] == '0')
        i++;
 
    // Update the index of leftmost '1' in str
    left_1 = i;
 
    // Stores the index of rightmost '1' in str
    int right_1;
    i = len - 1;
    while (i >= 0 && str[i] == '0')
        i--;
 
    // Update the index of rightmost '1' in str
    right_1 = i;
 
    // If str does not contain any '1's
    if (left_1 == len && right_1 == -1) {
 
        // No changes required
        cout << 0;
        return;
    }
 
    // Stores minimum cost
    int cost = a, zeroes;
 
    // Iterating through str form
    // left_1 to right_1
    for (i = left_1; i <= right_1; i++) {
 
        // Stores length of
        // consecutive 0s
        zeroes = 0;
 
        // Calculate length of consecutive 0s
        while (i < len && str[i] == '0') {
 
            zeroes++;
            i++;
        }
 
        // If a substring of 0s exists
        if (zeroes)
 
            // Update minimum cost
            cost += min(zeroes * b, a);
    }
    // Printing the minimum cost
    cout << cost;
}
 
// Driver Code
int main()
{
    string str = "01101110";
    int A = 5, B = 1;
    convert_to_allzeroes(str, A, B);
    return 0;
}


Java
// Java program to implement
// the above approach
class GFG{
     
// Function to find the minimum cost
// to convert given string to 0s only
public static void convert_to_allzeroes(String str,
                                        int a, int b)
{
     
    // Length of string
    int len = str.length();
   
    // Stores the index of leftmost '1' in str
    int left_1, i = 0;
   
    while (i < len && str.charAt(i) == '0')
        i++;
   
    // Update the index of leftmost '1' in str
    left_1 = i;
   
    // Stores the index of rightmost '1' in str
    int right_1;
    i = len - 1;
     
    while (i >= 0 && str.charAt(i) == '0')
        i--;
   
    // Update the index of rightmost '1' in str
    right_1 = i;
   
    // If str does not contain any '1's
    if (left_1 == len && right_1 == -1)
    {
         
        // No changes required
        System.out.print(0);
        return;
    }
   
    // Stores minimum cost
    int cost = a, zeroes;
   
    // Iterating through str form
    // left_1 to right_1
    for(i = left_1; i <= right_1; i++)
    {
         
        // Stores length of
        // consecutive 0s
        zeroes = 0;
   
        // Calculate length of consecutive 0s
        while (i < len && str.charAt(i) == '0')
        {
            zeroes++;
            i++;
        }
   
        // If a substring of 0s exists
        if (zeroes != 0)
   
            // Update minimum cost
            cost += Math.min(zeroes * b, a);
    }
     
    // Printing the minimum cost
    System.out.print(cost);
}
 
// Driver code
public static void main(String[] args)
{
    String str = "01101110";
    int A = 5, B = 1;
     
    convert_to_allzeroes(str, A, B);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# cost to convert given string
# to 0s only
def convert_to_allzeroes(st,
                         a, b):
 
    # Length of string
    length = len(st)
 
    # Stores the index of
    # leftmost '1' in str
    left_1 = 0
    i = 0
 
    while (i < length and
           st[i] == '0'):
        i += 1
 
    # Update the index of
    # leftmost '1' in str
    left_1 = i
 
    # Stores the index of
    # rightmost '1' in str
    right_1 = 0
    i = length - 1
     
    while (i >= 0 and
           st[i] == '0'):
        i -= 1
 
    # Update the index of
    # rightmost '1' in str
    right_1 = i
 
    # If str does not contain
    # any '1's
    if (left_1 == length and
        right_1 == -1):
 
        # No changes required
        print(0)
        return
 
    # Stores minimum cost
    cost = a
 
    # Iterating through str form
    # left_1 to right_1
    for i in range(left_1,
                   right_1 + 1):
 
        # Stores length of
        # consecutive 0s
        zeroes = 0
 
        # Calculate length of
        # consecutive 0s
        while (i < length and
               st[i] == '0'):
            zeroes += 1
            i += 1
 
        # If a substring of
        # 0s exists
        if (zeroes):
 
            # Update minimum cost
            cost += min(zeroes * b, a)
 
    # Printing the minimum cost
    print(cost)
 
# Driver Code
if __name__ == "__main__":
 
    st = "01101110"
    A = 5
    B = 1
    convert_to_allzeroes(st, A, B)
 
# This code is contributed by Chitranayal


C#
// C# program to implement
// the above approach 
using System;
 
class GFG{
      
// Function to find the minimum cost
// to convert given string to 0s only
public static void convert_to_allzeroes(string str,
                                        int a, int b)
{
     
    // Length of string
    int len = str.Length;
    
    // Stores the index of leftmost '1' in str
    int left_1, i = 0;
    
    while (i < len && str[i] == '0')
        i++;
    
    // Update the index of leftmost '1' in str
    left_1 = i;
    
    // Stores the index of rightmost '1' in str
    int right_1;
    i = len - 1;
      
    while (i >= 0 && str[i] == '0')
        i--;
    
    // Update the index of rightmost '1' in str
    right_1 = i;
    
    // If str does not contain any '1's
    if (left_1 == len && right_1 == -1)
    {
         
        // No changes required
        Console.Write(0);
        return;
    }
    
    // Stores minimum cost
    int cost = a, zeroes;
    
    // Iterating through str form
    // left_1 to right_1
    for(i = left_1; i <= right_1; i++)
    {
         
        // Stores length of
        // consecutive 0s
        zeroes = 0;
    
        // Calculate length of consecutive 0s
        while (i < len && str[i] == '0')
        {
            zeroes++;
            i++;
        }
    
        // If a substring of 0s exists
        if (zeroes != 0)
         
            // Update minimum cost
            cost += Math.Min(zeroes * b, a);
    }
      
    // Printing the minimum cost
    Console.Write(cost);
}
  
// Driver code
public static void Main()
{
    string str = "01101110";
    int A = 5, B = 1;
     
    convert_to_allzeroes(str, A, B);
}
}
 
// This code is contributed by susmitakundugoaldanga


Javascript


输出:
6

时间复杂度: O(N),其中 N 是字符串的长度。
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程