📌  相关文章
📜  最小化将给定字符串转换为长度为 K 的相等子字符串串联的成本

📅  最后修改于: 2021-09-06 06:34:27             🧑  作者: Mango

给定长度的字符串S N包括小写字母和整数K,其中N%K = 0,任务是找到通过执行给定的字符串转换成相同的K -length子串的串联的字符串的最小成本以下操作:

  • 一个字符可以替换为另一个字符。
  • 每个操作的成本是被替换字符和被替换字符之间的绝对差值。例如,如果将‘a’替换为‘z’ ,则操作成本为|”a”-“z”| = 25

例子:

朴素的方法:最简单的方法是生成长度为K 的所有可能的排列,并找到转换给定字符串的成本,使其具有长度为K的重复模式。然后,打印其中的最小成本。

时间复杂度: O(N*K 26 ),其中 N 是给定字符串的长度,K 是给定整数。
辅助空间: O(N)

有效的方法:想法是使用贪婪技术并观察对于从0K – 1 的任何位置i ,位置i + j * K处的字符必须相同,其中0 ≤ j < N/K 。例如,如果S =“abcbbc”K = 3,则在位置03的字符必须是相等的,在在2514位必须在相同的字符,以及字符必须是相等的。因此,可以单独计算位置i + j * K处的字符的最小成本。请按照以下步骤解决问题:

  • 初始化变量an以存储所需的最低成本。
  • [0, K – 1]范围内遍历字符串。
  • 对于每个位置i,找到放置一个字符的位置处的成本I + J * K,为每一个字符,其中0≤Ĵ计算其中的最小成本并更新ans
  • 完成上述步骤后,打印ans的值作为所需的最小成本。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find minimum cost
// to convert given String into
// String of K length same subString
void minCost(string s, int k)
{
     
    // Stores length of String
    int n = s.size();
     
    // Stores the minimum cost
    int ans = 0;
 
    // Traverse left subString
    // of k length
    for(int i = 0; i < k; i++)
    {
         
        // Stores the frequency
        int a[26];
         
        for(int p = 0; p < 26; p++)
        {
            a[p] = 0;
        }
 
        for(int j = i; j < n; j += k)
        {
            a[s[j] - 'a']++;
        }
 
        // Stores minimum cost for
        // sequence of S[i]%k indices
        int min_cost = INT_MAX;
 
        // Check for optimal character
        for(int ch = 0; ch < 26; ch++)
        {
            int cost = 0;
 
            // Find sum of distance 'a'+ ch
            // from character S[i]%k indices
            for(int tr = 0; tr < 26; tr++)
                cost += abs(ch - tr) * a[tr];
 
            // Choose minimum cost for
            // each index i
            min_cost = min(min_cost, cost);
        }
         
        // Increment ans
        ans += min_cost;
    }
 
    // Print minimum cost to
    // convert String
    cout << (ans);
}
 
// Driver Code
int main()
{
     
    // Given String S
    string S = "abcdefabc";
 
    int K = 3;
 
    // Function Call
    minCost(S, K);
}
 
// This code is contributed by gauravrajput1


Java
// Java program for the above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to find minimum cost
    // to convert given string into
    // string of K length same substring
    static void minCost(String s, int k)
    {
        // Stores length of string
        int n = s.length();
 
        // Stores the minimum cost
        int ans = 0;
 
        // Traverse left substring
        // of k length
        for (int i = 0; i < k; i++) {
 
            // Stores the frequency
            int[] a = new int[26];
 
            for (int j = i; j < n; j += k) {
                a[s.charAt(j) - 'a']++;
            }
 
            // Stores minimum cost for
            // sequence of S[i]%k indices
            int min_cost
                = Integer.MAX_VALUE;
 
            // Check for optimal character
            for (int ch = 0; ch < 26; ch++) {
 
                int cost = 0;
 
                // Find sum of distance 'a'+ ch
                // from character S[i]%k indices
                for (int tr = 0; tr < 26; tr++)
                    cost += Math.abs(ch - tr)
                            * a[tr];
 
                // Choose minimum cost for
                // each index i
                min_cost = Math.min(min_cost,
                                    cost);
            }
 
            // Increment ans
            ans += min_cost;
        }
 
        // Print minimum cost to
        // convert string
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given string S
        String S = "abcdefabc";
 
        int K = 3;
 
        // Function Call
        minCost(S, K);
    }
}


Python3
# Python3 program for the
# above approach
import sys
 
# Function to find minimum cost
# to convert given string into
# string of K length same substring
def minCost(s, k):
      
    # Stores length of string
    n = len(s)
  
    # Stores the minimum cost
    ans = 0
  
    # Traverse left substring
    # of k length
    for i in range(k):
          
        # Stores the frequency
        a = [0] * 26
  
        for j in range(i, n, k):
            a[ord(s[j]) - ord('a')] += 1
         
        # Stores minimum cost for
        # sequence of S[i]%k indices
        min_cost = sys.maxsize - 1
  
        # Check for optimal character
        for ch in range(26):
            cost = 0
              
            # Find sum of distance 'a'+ ch
            # from character S[i]%k indices
            for tr in range(26):
                cost += abs(ch - tr) * a[tr]
  
            # Choose minimum cost for
            # each index i
            min_cost = min(min_cost,
                               cost)
                                
        # Increment ans
        ans += min_cost
     
    # Print minimum cost to
    # convert string
    print(ans)
 
# Driver Code
      
# Given string S
S = "abcdefabc"
  
K = 3
  
# Function call
minCost(S, K)
 
# This code is contributed by code_hunt


C#
// C# program for the
// above approach
using System;
 
class GFG{
  
// Function to find minimum cost
// to convert given string into
// string of K length same substring
static void minCost(string s, int k)
{
     
    // Stores length of string
    int n = s.Length;
 
    // Stores the minimum cost
    int ans = 0;
 
    // Traverse left substring
    // of k length
    for(int i = 0; i < k; i++)
    {
         
        // Stores the frequency
        int[] a = new int[26];
 
        for(int j = i; j < n; j += k)
        {
            a[s[j] - 'a']++;
        }
 
        // Stores minimum cost for
        // sequence of S[i]%k indices
        int min_cost = Int32.MaxValue;
 
        // Check for optimal character
        for(int ch = 0; ch < 26; ch++)
        {
            int cost = 0;
             
            // Find sum of distance 'a'+ ch
            // from character S[i]%k indices
            for(int tr = 0; tr < 26; tr++)
                cost += Math.Abs(ch - tr) * a[tr];
 
            // Choose minimum cost for
            // each index i
            min_cost = Math.Min(min_cost,
                                cost);
        }
 
        // Increment ans
        ans += min_cost;
    }
 
    // Print minimum cost to
    // convert string
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
     
    // Given string S
    string S = "abcdefabc";
 
    int K = 3;
 
    // Function call
    minCost(S, K);
}
}
 
// This code is contributed by sanjoy_62


Javascript


输出:
9

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live