📌  相关文章
📜  最小化将每个不同字符的所有出现转换为小写或大写的成本

📅  最后修改于: 2021-09-06 05:55:40             🧑  作者: Mango

给定一个字符串SN个字母和两个正整数LU,代表转换任何字符为小写和分别大写的成本,该任务是修改字符串s,使得在字符串S字母表的每次出现是任一小写或大写,并且将原始字符串转换为修改后的字符串的成本必须最小。

例子:

方法:给定的问题可以通过使用贪心方法来解决,其思想是检查将所有出现的字符转换为小写的成本是否小于大写的成本,然后将其所有出现的转换为小写。否则,将所有出现的地方转换为大写。请按照以下步骤解决问题:

  • 将所有小写和大写字符的频率分别存储在数组lowerFreq[26]upperFreq[26] 中
  • 初始化另一个数组,比如result[26]0 ,其中result[i] = 1表示第i字符需要小写,否则需要大写。
  • 使用变量i在范围[0, 25] 上迭代并执行以下步骤:
    • 将每次出现的字符i转换为小写和大写的成本分别存储在变量costLowercostUpper 中
    • 乘以的成本为1个字符转换为小写的,即,L以其大写的频率,即,upperFreq [I]找到costLower的值。类似地,通过将U乘以lowerFreq[i] 来找到costUpper的值。
    • 如果costLower < costUpper的值,则将result[i]的值更新为1
  • 使用变量i遍历字符串S并执行以下步骤:
    • S[i]的索引存储在变量X 中
    • 如果result[i] 的值等于1 ,则将S[i]转换为其小写。否则,将 S[i] 转换为大写。
  • 完成上述步骤后,将字符串S打印为修改后的字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the minimum cost
// to convert all distinct characters
// to either uppercase or lowercase
void minimumCost(string s, int L, int U)
{
    // Store the size of the string
    int N = s.size();
 
    string ans = "";
 
    // Stores the frequency of lowercase
    // & uppercase characters respectively
    int lowerFreq[26] = { 0 };
    int upperFreq[26] = { 0 };
 
    // Traverse the string S
    for (int i = 0; i < N; i++) {
 
        // Update uppercase
        // frequency of s[i]
        if (isupper(s[i]))
            upperFreq[s[i] - 'A']++;
 
        // Otherwise, update lowercase
        // frequency of s[i]
        else
            lowerFreq[s[i] - 'a']++;
    }
 
    // Stores if the i-th character
    //should be lowercase or not
    int result[26] = { 0 };
 
    // Iterate over the range [0, 25]
    for (int i = 0; i < 26; i++) {
 
        // If the character is present
        // in the string
        if (lowerFreq[i] != 0
            || upperFreq[i] != 0) {
 
            // Store the cost to convert
            // every occurence of i to
            // uppercase and lowercase
            int costToUpper = U * lowerFreq[i];
            int costToLower = L * upperFreq[i];
 
            // Update result[i] to 1 if
            // lowercase cost is less
            if (costToLower < costToUpper) {
                result[i] = 1;
            }
        }
    }
 
    // Traverse the string S
    for (int i = 0; i < N; i++) {
 
        // Store the index
        // of the character
        int index = 0;
 
        if (islower(s[i]))
            index = s[i] - 'a';
        else
            index = s[i] - 'A';
 
        // Convert the current character
        // to uppercase or lowercase
        // according to the condition
        if (result[index] == 1) {
 
            // Update s[i]
            s[i] = tolower(s[i]);
        }
        else {
 
            // Update s[i]
            s[i] = toupper(s[i]);
        }
    }
 
    // Print the modified string
    cout << s;
}
 
// Driver Code
int main()
{
    string S = "aabbAA";
    int L = 1, U = 1;
    minimumCost(S, L, U);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the minimum cost
// to convert all distinct characters
// to either uppercase or lowercase
static void minimumCost(String str, int L, int U)
{
     
    // Store the size of the string
    int N = str.length();
    char s[] = str.toCharArray();
 
    String ans = "";
 
    // Stores the frequency of lowercase
    // & uppercase characters respectively
    int lowerFreq[] = new int[26];
    int upperFreq[] = new int[26];
 
    // Traverse the string S
    for(int i = 0; i < N; i++)
    {
         
        // Update uppercase
        // frequency of s[i]
        if (Character.isUpperCase(s[i]))
            upperFreq[s[i] - 'A']++;
 
        // Otherwise, update lowercase
        // frequency of s[i]
        else
            lowerFreq[s[i] - 'a']++;
    }
 
    // Stores if the i-th character
    // should be lowercase or not
    int result[] = new int[26];
 
    // Iterate over the range [0, 25]
    for(int i = 0; i < 26; i++)
    {
         
        // If the character is present
        // in the string
        if (lowerFreq[i] != 0 || upperFreq[i] != 0)
        {
             
            // Store the cost to convert
            // every occurence of i to
            // uppercase and lowercase
            int costToUpper = U * lowerFreq[i];
            int costToLower = L * upperFreq[i];
 
            // Update result[i] to 1 if
            // lowercase cost is less
            if (costToLower < costToUpper)
            {
                result[i] = 1;
            }
        }
    }
 
    // Traverse the string S
    for(int i = 0; i < N; i++)
    {
         
        // Store the index
        // of the character
        int index = 0;
 
        if (Character.isLowerCase(s[i]))
            index = s[i] - 'a';
        else
            index = s[i] - 'A';
 
        // Convert the current character
        // to uppercase or lowercase
        // according to the condition
        if (result[index] == 1)
        {
             
            // Update s[i]
            s[i] = Character.toLowerCase(s[i]);
        }
        else
        {
             
            // Update s[i]
            s[i] = Character.toUpperCase(s[i]);
        }
    }
 
    // Print the modified string
    System.out.println(new String(s));
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "aabbAA";
    int L = 1, U = 1;
    minimumCost(S, L, U);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for above approach
 
# Function to find the minimum cost
# to convert all distinct characters
# to either uppercase or lowercase
def minimumCost(s, L, U):
     
    ans = []
 
    # Stores the frequency of lowercase
    # & uppercase characters respectively
    lowerFreq = [0] * 26
    upperFreq = [0] * 26
 
    # Traverse the string S
    for c in s:
        if c.isupper():
 
        # Update uppercase
        # frequency of s[i]
            upperFreq[ord(c) - ord('A')] += 1
 
        # Otherwise, update lowercase
        # frequency of s[i]
        else:
            lowerFreq[ord(c) - ord('a')] += 1
 
    # stores if the i-th character
    # should be lowercase or not
    result = [0] * 26
 
    # Iterate over the range [0, 25]
    for i in range(26):
 
        # If the character is present
        # in the string
        if lowerFreq[i] != 0 or upperFreq[i] != 0:
 
            # Store the cost to convert
            # every occurence of i to
            # uppercase and lowercase
            costToUpper = U * lowerFreq[i];
            costToLower = L * upperFreq[i];
 
            # Update result[i] to 1 if
            # lowercase cost is less
            if costToLower < costToUpper:
                result[i] = 1
 
    # Traverse the string S
    for i in range(len(s)):
 
        # Store the index
        # of the character
        index = 0
 
        if s[i].islower():
            index = ord(s[i]) - ord('a')
        else:
            index = ord(s[i]) - ord('A')
 
        # Convert the current character
        # to uppercase or lowercase
        # according to the condition
        if result[index] == 1:
 
            # Update the character at the
            # ith index of s
            ans.append(s[i].lower())
        else:
 
            # Update the character at the
            # ith index of s
            ans.append(s[i].upper())
 
    s = ''.join(ans)
     
    # Print the modified string
    print(s)
 
# Driver code
S = "aabbAA"
L = 1
U = 1
 
minimumCost(S, L, U)
 
# This code is contributed by Md Zaid Alam


C#
// C# program for the above approach
using System;
 
class GFG {
 
    // Function to find the minimum cost
    // to convert all distinct characters
    // to either uppercase or lowercase
    static void minimumCost(string str, int L, int U)
    {
 
        // Store the size of the string
        int N = str.Length;
        char[] s = str.ToCharArray();
 
        // string ans = "";
 
        // Stores the frequency of lowercase
        // & uppercase characters respectively
        int[] lowerFreq = new int[26];
        int[] upperFreq = new int[26];
 
        // Traverse the string S
        for (int i = 0; i < N; i++) {
 
            // Update uppercase
            // frequency of s[i]
            if (char.IsUpper(s[i]))
                upperFreq[s[i] - 'A']++;
 
            // Otherwise, update lowercase
            // frequency of s[i]
            else
                lowerFreq[s[i] - 'a']++;
        }
 
        // Stores if the i-th character
        // should be lowercase or not
        int[] result = new int[26];
 
        // Iterate over the range [0, 25]
        for (int i = 0; i < 26; i++) {
 
            // If the character is present
            // in the string
            if (lowerFreq[i] != 0 || upperFreq[i] != 0) {
 
                // Store the cost to convert
                // every occurence of i to
                // uppercase and lowercase
                int costToUpper = U * lowerFreq[i];
                int costToLower = L * upperFreq[i];
 
                // Update result[i] to 1 if
                // lowercase cost is less
                if (costToLower < costToUpper) {
                    result[i] = 1;
                }
            }
        }
 
        // Traverse the string S
        for (int i = 0; i < N; i++) {
 
            // Store the index
            // of the character
            int index = 0;
 
            if (char.IsLower(s[i]))
                index = s[i] - 'a';
            else
                index = s[i] - 'A';
 
            // Convert the current character
            // to uppercase or lowercase
            // according to the condition
            if (result[index] == 1) {
 
                // Update s[i]
                s[i] = char.ToLower(s[i]);
            }
            else {
 
                // Update s[i]
                s[i] = char.ToUpper(s[i]);
            }
        }
 
        // Print the modified string
        Console.WriteLine(new string(s));
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string S = "aabbAA";
        int L = 1, U = 1;
        minimumCost(S, L, U);
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
AAbbAA

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

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