📌  相关文章
📜  使字符串的所有剩余字符唯一所需的删除成本最小化

📅  最后修改于: 2021-10-27 07:22:49             🧑  作者: Mango

给定一个字符串str和一个大小为N的数组cost[] ,其中cost[i]表示从字符串str 中删除第i字符的成本,任务是找到使字符串的每个字符所需的最小删除成本独特的。

例子:

朴素的方法:解决问题的最简单的方法是遍历字符串,对于每个字符,遍历剩余的字符并找到它的出现次数。存储删除事件的最大成本。将删除所有其他出现的字符的成本添加到总和中。最后,在对字符串 的所有字符完成此操作后,打印获得的最终总和。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum cost of
// removing characters to make the String unique
int delCost(string s, int cost[], int l1, int l2)
{
 
    // stores the visited character
    bool visited[l1];
    memset(visited, 0, sizeof(visited));
   
    // stores the answer
    int ans = 0;
 
    // traverse the String
    for (int i = 0; i < l1; i++)
    {
 
        // if already visited
        if (visited[i])
        {
            continue;
        }
 
        // Stores the maximum cost of
        // removing a particular character
        int maxDel = 0;
 
        // Store the total deletion cost of
        // a particular character
        int totalCost = 0;
 
        // Mark the current character visited
        visited[i] = 1;
 
        // Traverse the indices of the String [i, N-1]
        for (int j = i; j < l1; j++)
        {
 
            // If any duplicate is found
            if (s[i] == s[j])
            {
 
                // Update the maximum cost
                // and total cost
                maxDel = max(maxDel, cost[j]);
                totalCost += cost[j];
 
                // Mark the current character visited
                visited[j] = 1;
            }
        }
 
        // Keep the character with
        // maximum cost and delete the rest
        ans += totalCost - maxDel;
    }
 
    // return the minimum cost
    return ans;
}
 
// Driver code
int main()
{
 
    // input String
    string s = "AAABBB";
    int l1 = s.size();
   
    // input array
    int cost[] = { 1, 2, 3, 4, 5, 6 };
    int l2 = sizeof(cost) / sizeof(cost[0]);
   
    // function call
    cout << delCost(s, cost, l1, l2);
    return 0;
}
 
// This code is contributed by gauravrajput1


Java
// Java program to implement
// the above approach
import java.io.*;
 
class GFG
{
 
  // Function to find the minimum cost of
  // removing characters to make the string unique
  public static int delCost(String s, int[] cost)
  {
 
    // stores the visited character
    boolean visited[] = new boolean[s.length()];
 
    // stores the answer
    int ans = 0;
 
    // traverse the string
    for (int i = 0; i < s.length(); i++)
    {
 
      // if already visited
      if (visited[i])
      {
        continue;
      }
 
      // Stores the maximum cost of
      // removing a particular character
      int maxDel = 0;
 
      // Store the total deletion cost of
      // a particular character
      int totalCost = 0;
 
      // Mark the current character visited
      visited[i] = true;
 
      // Traverse the indices of the string [i, N-1]
      for (int j = i; j < s.length(); j++)
      {
 
        // If any duplicate is found
        if (s.charAt(i) == s.charAt(j))
        {
 
          // Update the maximum cost
          // and total cost
          maxDel = Math.max(maxDel, cost[j]);
          totalCost += cost[j];
 
          // Mark the current character visited
          visited[j] = true;
        }
      }
 
      // Keep the character with
      // maximum cost and delete the rest
      ans += totalCost - maxDel;
    }
 
    // return the minimum cost
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // input string
    String s = "AAABBB";
 
    // input array
    int[] cost = { 1, 2, 3, 4, 5, 6 };
 
    // function call
    System.out.println(delCost(s, cost));
  }
}
 
// This code is contributed by aditya7409


Python3
# Python3 program to implement
# the above approach
 
# Function to find the minimum cost of
# removing characters to make the string unique
def delCost(s, cost):
   
    # Stores the visited characters
    visited = [False]*len(s)
     
    # Stores the answer
    ans = 0
     
    # Traverse the string
    for i in range(len(s)):
       
          # If already visited
        if visited[i]: 
            continue
     
        # Stores the maximum cost of
        # removing a particular character
        maxDel = 0
 
        # Store the total deletion cost of
        # a particular character
        totCost = 0
         
        # Mark the current character visited
        visited[i] = True
         
        # Traverse the indices of the string [i, N-1]
        for j in range(i, len(s)):
           
            # If any duplicate is found
            if s[i] == s[j]: 
                 
                # Update the maximum cost
                # and total cost
                maxDel = max(maxDel, cost[j])
                totCost += cost[j]
                 
                # Mark the current character visited
                visited[j] = True
         
        # Keep the character with
        # maximum cost and delete the rest
        ans += totCost - maxDel
         
       # Return the minimum cost
    return ans
 
# Driver code
# Given string
string = "AAABBB"
 
# Given cost array
cost = [1, 2, 3, 4, 5, 6]
 
# Function Call
print(delCost(string, cost))


C#
// C# program to implement
// the above approach 
using System;
using System.Collections.Generic;
 
class GFG{
         
// Function to find the minimum cost of
// removing characters to make the string unique
public static int delCost(string s, int[] cost)
{
     
    // Stores the visited character
    bool[] visited = new bool[s.Length];
     
    // Stores the answer
    int ans = 0;
     
    // Traverse the string
    for(int i = 0; i < s.Length; i++)
    {
         
        // If already visited
        if (visited[i] != false)
        {
            continue;
        }
         
        // Stores the maximum cost of
        // removing a particular character
        int maxDel = 0;
         
        // Store the total deletion cost of
        // a particular character
        int totalCost = 0;
         
        // Mark the current character visited
        visited[i] = true;
         
        // Traverse the indices of the
        // string [i, N-1]
        for(int j = i; j < s.Length; j++)
        {
             
            // If any duplicate is found
            if (s[i] == s[j])
            {
                 
                // Update the maximum cost
                // and total cost
                maxDel = Math.Max(maxDel, cost[j]);
                totalCost += cost[j];
                 
                // Mark the current character visited
                visited[j] = true;
            }
        }
         
        // Keep the character with
        // maximum cost and delete
        // the rest
        ans += totalCost - maxDel;
    }
     
    // Return the minimum cost
    return ans;
}
 
// Driver Code   
public static void Main ()   
{   
     
    // Input string
    string s = "AAABBB";
     
    // Input array
    int[] cost = { 1, 2, 3, 4, 5, 6 };
     
    // Function call
    Console.Write(delCost(s, cost));
}
}
 
// This code is contributed by code_hunt


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum cost of
// removing characters to make the string unique
int delCost(string s, int cost[])
{
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    map forMax;
 
    // Create a dictionary to store the total
    // deletion cost of a character
    map forTot;
 
    // Traverse the string, S
    for (int i = 0; i < s.length(); i++) {
 
        // Keep track of maximum cost of each character
        if (!forMax[s[i]]) {
            forMax[s[i]] = cost[i];
        }
        else {
 
            // Update the maximum deletion cost
            forMax[s[i]] = max(cost[i], forMax[s[i]]);
        }
 
        // Keep track of the total cost of each character
        if (!forTot[s[i]]) {
            forTot[s[i]] = cost[i];
        }
        else {
 
            // Update the total deletion cost
            forTot[s[i]] = forTot[s[i]] + cost[i];
        }
    }
 
    // Traverse through all the unique characters
    for (auto i : forMax) {
 
        // Keep the maximum cost character and
        // delete the rest
        ans += forTot[i.first] - i.second;
    }
 
    // Return the answer
    return ans;
}
 
// Driver code
int main()
{
 
    // Given string
    string s = "AAABBB";
 
    // Given cost array
    int cost[] = { 1, 2, 3, 4, 5, 6 };
 
    // Function Call
    cout << (delCost(s, cost));
}
 
// This code is contributed by ukasp.


Java
// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to find the minimum cost of
  // removing characters to make the string unique
  static int delCost(String s, int[] cost)
  {
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    HashMap forMax = new HashMap<>();
 
    // Create a dictionary to store the total
    // deletion cost of a character
    HashMap forTot = new HashMap<>();
 
    // Traverse the string, S
    for(int i = 0; i < s.length(); i++)
    {
 
      // Keep track of maximum cost of each character
      if(!forMax.containsKey(s.charAt(i)))
      {
        forMax.put(s.charAt(i), cost[i]);
      }
      else
      {
 
        // Update the maximum deletion cost
        forMax.put(s.charAt(i), Math.max(cost[i], forMax.get(s.charAt(i))));
      }
 
      // Keep track of the total cost of each character
      if(!forTot.containsKey(s.charAt(i)))
      {
        forTot.put(s.charAt(i), cost[i]);
      }
      else
      {
 
        // Update the total deletion cost
        forTot.put(s.charAt(i), forTot.get(s.charAt(i)) + cost[i]);
      }
    }
 
    // Traverse through all the unique characters
    for (Map.Entry i : forMax.entrySet())
    {
 
      // Keep the maximum cost character and
      // delete the rest
      ans += forTot.get(i.getKey()) - i.getValue();
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given string
    String s = "AAABBB";
 
    // Given cost array
    int[] cost = {1, 2, 3, 4, 5, 6};
 
    // Function Call
    System.out.println(delCost(s, cost));
  }
}
 
// This code is contributed by divyeshrabaddiya07.


Python3
# Python3 program to implement
# the above approach
 
# Function to find the minimum cost of
# removing characters to make the string unique
def delCost(s, cost):
   
    # Store the minimum cost required
    ans = 0
     
    # Create a dictionary to store the
    # maximum cost of removal a character
    forMax = {}
     
    # Create a dictionary to store the total
    # deletion cost of a character
    forTot = {}
     
    # Traverse the string, S
    for i in range(len(s)):
       
          # Keep track of maximum cost of each character
        if s[i] not in forMax: 
            forMax[s[i]] = cost[i]
        else:
           
              # Update the maximum deletion cost
            forMax[s[i]] = max(cost[i], forMax[s[i]])
 
        # Keep track of the total cost of each character
        if s[i] not in forTot: 
            forTot[s[i]] = cost[i]
        else:
           
              # Update the total deletion cost
            forTot[s[i]] += cost[i]
 
    # Traverse through all the unique characters
    for i in forMax:
       
          # Keep the maximum cost character and
        # delete the rest
        ans += forTot[i] - forMax[i]
         
    # Return the answer
    return ans
 
# Driver code
# Given string
string = "AAABBB"
 
# Given cost array
cost = [1, 2, 3, 4, 5, 6]
 
# Function Call
print(delCost(string, cost))


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find the minimum cost of
  // removing characters to make the string unique
  static int delCost(string s, int[] cost)
  {
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    Dictionary forMax = new Dictionary();
 
    // Create a dictionary to store the total
    // deletion cost of a character
    Dictionary forTot = new Dictionary();
 
    // Traverse the string, S
    for(int i = 0; i < s.Length; i++)
    {
 
      // Keep track of maximum cost of each character
      if(!forMax.ContainsKey(s[i]))
      {
        forMax[s[i]] = cost[i];
      }
      else
      {
 
        // Update the maximum deletion cost
        forMax[s[i]] = Math.Max(cost[i], forMax[s[i]]);
      }
 
      // Keep track of the total cost of each character
      if(!forTot.ContainsKey(s[i]))
      {
        forTot[s[i]] = cost[i];
      }
      else
      {
 
        // Update the total deletion cost
        forTot[s[i]] += cost[i];
      }
    }
 
    // Traverse through all the unique characters
    foreach(KeyValuePair i in forMax)
    {
 
      // Keep the maximum cost character and
      // delete the rest
      ans += forTot[i.Key] - i.Value;
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver code
  static void Main()
  {
 
    // Given string
    string s = "AAABBB";
 
    // Given cost array
    int[] cost = {1, 2, 3, 4, 5, 6};
 
    // Function Call
    Console.WriteLine(delCost(s, cost));
  }
}
 
// This code is contributed by divyesh072019


Javascript


输出:
12

时间复杂度: O(N 2 )
辅助空间: O(N)

高效的方法:为了优化上述方法,想法是使用Hashmap。请按照以下步骤解决问题:

  • 初始化一个变量,比如ans ,以存储所需的最低成本。
  • 初始化两个 Hashmap,比如forMaxforTot ,分别存储每个字符的最大和总移除成本。
  • 使用变量i遍历字符串S
    • 更新forMax[s[i]] = max(forMax(s[i]), cost[i])
    • 更新forTot[s[i]] += cost[i]
  • 遍历 Hashmap forMax
    • 对于每个字符,保留最大成本字符并通过更新ans += forTot[i]-forMax[i]删除其其他重复项。
  • 打印答案

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum cost of
// removing characters to make the string unique
int delCost(string s, int cost[])
{
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    map forMax;
 
    // Create a dictionary to store the total
    // deletion cost of a character
    map forTot;
 
    // Traverse the string, S
    for (int i = 0; i < s.length(); i++) {
 
        // Keep track of maximum cost of each character
        if (!forMax[s[i]]) {
            forMax[s[i]] = cost[i];
        }
        else {
 
            // Update the maximum deletion cost
            forMax[s[i]] = max(cost[i], forMax[s[i]]);
        }
 
        // Keep track of the total cost of each character
        if (!forTot[s[i]]) {
            forTot[s[i]] = cost[i];
        }
        else {
 
            // Update the total deletion cost
            forTot[s[i]] = forTot[s[i]] + cost[i];
        }
    }
 
    // Traverse through all the unique characters
    for (auto i : forMax) {
 
        // Keep the maximum cost character and
        // delete the rest
        ans += forTot[i.first] - i.second;
    }
 
    // Return the answer
    return ans;
}
 
// Driver code
int main()
{
 
    // Given string
    string s = "AAABBB";
 
    // Given cost array
    int cost[] = { 1, 2, 3, 4, 5, 6 };
 
    // Function Call
    cout << (delCost(s, cost));
}
 
// This code is contributed by ukasp.

Java

// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to find the minimum cost of
  // removing characters to make the string unique
  static int delCost(String s, int[] cost)
  {
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    HashMap forMax = new HashMap<>();
 
    // Create a dictionary to store the total
    // deletion cost of a character
    HashMap forTot = new HashMap<>();
 
    // Traverse the string, S
    for(int i = 0; i < s.length(); i++)
    {
 
      // Keep track of maximum cost of each character
      if(!forMax.containsKey(s.charAt(i)))
      {
        forMax.put(s.charAt(i), cost[i]);
      }
      else
      {
 
        // Update the maximum deletion cost
        forMax.put(s.charAt(i), Math.max(cost[i], forMax.get(s.charAt(i))));
      }
 
      // Keep track of the total cost of each character
      if(!forTot.containsKey(s.charAt(i)))
      {
        forTot.put(s.charAt(i), cost[i]);
      }
      else
      {
 
        // Update the total deletion cost
        forTot.put(s.charAt(i), forTot.get(s.charAt(i)) + cost[i]);
      }
    }
 
    // Traverse through all the unique characters
    for (Map.Entry i : forMax.entrySet())
    {
 
      // Keep the maximum cost character and
      // delete the rest
      ans += forTot.get(i.getKey()) - i.getValue();
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given string
    String s = "AAABBB";
 
    // Given cost array
    int[] cost = {1, 2, 3, 4, 5, 6};
 
    // Function Call
    System.out.println(delCost(s, cost));
  }
}
 
// This code is contributed by divyeshrabaddiya07.

蟒蛇3

# Python3 program to implement
# the above approach
 
# Function to find the minimum cost of
# removing characters to make the string unique
def delCost(s, cost):
   
    # Store the minimum cost required
    ans = 0
     
    # Create a dictionary to store the
    # maximum cost of removal a character
    forMax = {}
     
    # Create a dictionary to store the total
    # deletion cost of a character
    forTot = {}
     
    # Traverse the string, S
    for i in range(len(s)):
       
          # Keep track of maximum cost of each character
        if s[i] not in forMax: 
            forMax[s[i]] = cost[i]
        else:
           
              # Update the maximum deletion cost
            forMax[s[i]] = max(cost[i], forMax[s[i]])
 
        # Keep track of the total cost of each character
        if s[i] not in forTot: 
            forTot[s[i]] = cost[i]
        else:
           
              # Update the total deletion cost
            forTot[s[i]] += cost[i]
 
    # Traverse through all the unique characters
    for i in forMax:
       
          # Keep the maximum cost character and
        # delete the rest
        ans += forTot[i] - forMax[i]
         
    # Return the answer
    return ans
 
# Driver code
# Given string
string = "AAABBB"
 
# Given cost array
cost = [1, 2, 3, 4, 5, 6]
 
# Function Call
print(delCost(string, cost))

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find the minimum cost of
  // removing characters to make the string unique
  static int delCost(string s, int[] cost)
  {
 
    // Store the minimum cost required
    int ans = 0;
 
    // Create a dictionary to store the
    // maximum cost of removal a character
    Dictionary forMax = new Dictionary();
 
    // Create a dictionary to store the total
    // deletion cost of a character
    Dictionary forTot = new Dictionary();
 
    // Traverse the string, S
    for(int i = 0; i < s.Length; i++)
    {
 
      // Keep track of maximum cost of each character
      if(!forMax.ContainsKey(s[i]))
      {
        forMax[s[i]] = cost[i];
      }
      else
      {
 
        // Update the maximum deletion cost
        forMax[s[i]] = Math.Max(cost[i], forMax[s[i]]);
      }
 
      // Keep track of the total cost of each character
      if(!forTot.ContainsKey(s[i]))
      {
        forTot[s[i]] = cost[i];
      }
      else
      {
 
        // Update the total deletion cost
        forTot[s[i]] += cost[i];
      }
    }
 
    // Traverse through all the unique characters
    foreach(KeyValuePair i in forMax)
    {
 
      // Keep the maximum cost character and
      // delete the rest
      ans += forTot[i.Key] - i.Value;
    }
 
    // Return the answer
    return ans;
  }
 
  // Driver code
  static void Main()
  {
 
    // Given string
    string s = "AAABBB";
 
    // Given cost array
    int[] cost = {1, 2, 3, 4, 5, 6};
 
    // Function Call
    Console.WriteLine(delCost(s, cost));
  }
}
 
// This code is contributed by divyesh072019

Javascript


输出:
12

时间复杂度: O(N)
辅助空间: O(N)

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