📌  相关文章
📜  通过替换空格将字符串转换为另一个字符串的最低成本

📅  最后修改于: 2022-05-13 01:57:06.842000             🧑  作者: Mango

通过替换空格将字符串转换为另一个字符串的最低成本

给定两个字符串s1s2 ,小写字母的长度为N 。字符串s1 和 s2 最初可能包含一些空格,任务是找到将字符串s1 转换为 s2 的最小操作。

  • 最初,如果有任何空格,它们应该被替换为任何相同的字符,成本为 0 和
  • 字符串中的任何元音都可以被任何辅音替换,任何辅音都可以被任何成本为 1 的元音替换。

例子:

方法:由于如果字符中有空格,则只有 26 个小写字符串,因此可以将空格替换为这些字符中的每一个,并且可以计算将字符串s1 转换为 s2 的最小成本。如果字符串的两个字符一个是元音,另一个是辅音,反之亦然,则转换一个字符只需一个单位。如果两个字符都是元音或辅音并且不相等,则它的成本为 2;辅音 -> 元音 -> 辅音(成本 = 2)或元音 -> 辅音 -> 元音(成本 = 2)。
按照以下步骤解决上述问题:

  • 如果两个字符串的长度不相等,则返回-1
  • 用长度和 res 初始化 n 为INT_MAX
  • 现在遍历26 个字符中的每一个。
  • 初始化变量ops = 0以存储所需的成本。
  • 从范围[0, n)遍历并检查任何字符串中是否有空格。
  • 如果有空白,则初始化字符c1c2以存储修改后的字符。
  • 如果两个字符c1 == c2 (替换空格后的字符)则不需要任何操作。
  • 否则,如果两者都是元音或辅音,则需要2 次操作,否则只需1次操作将其添加到 ops 变量中。
  • 遍历后将最小操作存储在res (min(ops, res))中。
  • 打印结果res

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check whether
// a character is vowel or not
bool isVowel(char c)
{
    return (c == 'a' || c == 'e' || c == 'i'
            || c == 'o' || c == 'u');
}
 
// Function to calculate minimum cost
void minCost(string s1, string s2)
{
    // If both the lengths are not equal
    if (s1.length() != s2.length()) {
        cout << -1 << endl;
        return;
    }
 
    int n = s1.length();
 
    // Initialize res with max value
    int res = INT_MAX;
 
    // Iterate through every character
    // and check the minimum cost by
    // replacing the blank by all letters
    for (char c = 'a'; c <= 'z'; c++) {
 
        // Initialize ops to check
        // the cost required by replacing
        // each char c
        int ops = 0;
        for (int i = 0; i < n; i++) {
 
            // If it is blank replace with c
            char c1 = s1[i] == '_' ? c : s1[i];
            char c2 = s2[i] == '_' ? c : s2[i];
 
            // If both are equal no ops required
            if (c1 == c2)
                continue;
            else {
 
                // If both are vowels or  consonants
                // it requires cost as two
                // vowel->consonant ->vowel
                // and vice versa
                // Else 1 operation
                ops
                    = ops
                      + (isVowel(s1[i]) != isVowel(s2[i])
                             ? 2
                             : 1);
            }
        }
 
        // Take the minimum
        if (ops < res) {
            res = ops;
        }
    }
 
    // Print the result
    cout << res << endl;
}
 
// Driver code
int main()
{
    // Initialize the strings
    string s1 = "g_e_s", s2 = "ge_ks";
 
    // Function call
    minCost(s1, s2);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class GFG
{
   
  // Function to check whether
  // a character is vowel or not
  static boolean isVowel(char c)
  {
    return (c == 'a' || c == 'e' || c == 'i'
            || c == 'o' || c == 'u');
  }
 
  // Function to calculate minimum cost
  static void minCost(String s1, String s2)
  {
     
    // If both the lengths are not equal
    if (s1.length() != s2.length()) {
      System.out.println(-1);
      return;
    }
 
    int n = s1.length();
 
    // Initialize res with max value
    int res = Integer.MAX_VALUE;
 
    // Iterate through every character
    // and check the minimum cost by
    // replacing the blank by all letters
    for (char c = 'a'; c <= 'z'; c++) {
 
      // Initialize ops to check
      // the cost required by replacing
      // each char c
      int ops = 0;
      for (int i = 0; i < n; i++) {
 
        // If it is blank replace with c
        char c1 = s1.charAt(i) == '_' ? c : s1.charAt(i);
        char c2 = s2.charAt(i) == '_' ? c : s2.charAt(i);
 
        // If both are equal no ops required
        if (c1 == c2)
          continue;
        else {
 
          // If both are vowels or  consonants
          // it requires cost as two
          // vowel->consonant ->vowel
          // and vice versa
          // Else 1 operation
          ops
            = ops
            + (isVowel(s1.charAt(i)) != isVowel(s2.charAt(i))
               ? 2
               : 1);
        }
      }
 
      // Take the minimum
      if (ops < res) {
        res = ops;
      }
    }
 
    // Print the result
   System.out.println(res);
  }
 
  // Driver code
  public static void main(String args[])
  {
     
    // Initialize the strings
    String s1 = "g_e_s", s2 = "ge_ks";
 
    // Function call
    minCost(s1, s2);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python 3 program for the above approach
import sys
 
# Function to check whether
# a character is vowel or not
def isVowel(c):
 
    return (c == 'a' or c == 'e' or c == 'i'
            or c == 'o' or c == 'u')
 
# Function to calculate minimum cost
def minCost(s1,  s2):
 
    # If both the lengths are not equal
    if (len(s1) != len(s2)):
        print(-1)
        return
 
    n = len(s1)
 
    # Initialize res with max value
    res = sys.maxsize
 
    # Iterate through every character
    # and check the minimum cost by
    # replacing the blank by all letters
 
    for c in range(ord('a'), ord('z')+1):
 
        # Initialize ops to check
        # the cost required by replacing
        # each char c
        ops = 0
        for i in range(n):
 
            # If it is blank replace with c
            if s1[i] == '_':
                c1 = chr(c)
            else:
                c1 = s1[i]
            if s2[i] == '_':
                c2 = chr(c)
            else:
                c2 = s2[i]
 
            # If both are equal no ops required
            if (c1 == c2):
                continue
            else:
 
                # If both are vowels or  consonants
                # it requires cost as two
                # vowel->consonant ->vowel
                # and vice versa
                # Else 1 operation
 
                if isVowel(s1[i]) != isVowel(s2[i]):
                    ops += 2
                else:
                    ops += 1
 
        # Take the minimum
        if (ops < res):
            res = ops
 
    # Print the result
    print(res)
 
# Driver code
if __name__ == "__main__":
 
    # Initialize the strings
    s1 = "g_e_s"
    s2 = "ge_ks"
 
    # Function call
    minCost(s1, s2)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
class GFG
{
   
  // Function to check whether
  // a character is vowel or not
  static bool isVowel(char c)
  {
    return (c == 'a' || c == 'e' || c == 'i'
            || c == 'o' || c == 'u');
  }
 
  // Function to calculate minimum cost
  static void minCost(string s1, string s2)
  {
     
    // If both the lengths are not equal
    if (s1.Length != s2.Length) {
      Console.WriteLine(-1);
      return;
    }
 
    int n = s1.Length;
 
    // Initialize res with max value
    int res = Int32.MaxValue;
 
    // Iterate through every character
    // and check the minimum cost by
    // replacing the blank by all letters
    for (char c = 'a'; c <= 'z'; c++) {
 
      // Initialize ops to check
      // the cost required by replacing
      // each char c
      int ops = 0;
      for (int i = 0; i < n; i++) {
 
        // If it is blank replace with c
        char c1 = s1[i] == '_' ? c : s1[i];
        char c2 = s2[i] == '_' ? c : s2[i];
 
        // If both are equal no ops required
        if (c1 == c2)
          continue;
        else {
 
          // If both are vowels or  consonants
          // it requires cost as two
          // vowel->consonant ->vowel
          // and vice versa
          // Else 1 operation
          ops
            = ops
            + (isVowel(s1[i]) != isVowel(s2[i])
               ? 2
               : 1);
        }
      }
 
      // Take the minimum
      if (ops < res) {
        res = ops;
      }
    }
 
    // Print the result
    Console.WriteLine(res);
  }
 
  // Driver code
  public static void Main()
  {
     
    // Initialize the strings
    string s1 = "g_e_s", s2 = "ge_ks";
 
    // Function call
    minCost(s1, s2);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
1

时间复杂度: O(26* N)
空间复杂度: O(1)