📌  相关文章
📜  使用最小给定操作数将一个字符串转换为另一个

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

使用最小给定操作数将一个字符串转换为另一个

给定两个字符串A 和 B,任务是尽可能将 A 转换为 B。唯一允许的操作是将 A 中的任何字符放入前面。查找是否可以转换字符串。如果是,则输出最小编号。转换所需的操作。

例子:

Input:  A = "ABD", B = "BAD"
Output: 1
Explanation: Pick B and insert it at front.

Input:  A = "EACBD", B = "EABCD"
Output: 3
Explanation: Pick B and insert at front, EACBD => BEACD
             Pick A and insert at front, BEACD => ABECD
             Pick E and insert at front, ABECD => EABCD

检查一个字符串是否可以转换为另一个字符串很简单。我们需要检查两个字符串是否具有相同数量的字符和相同的字符集。这可以通过为第一个字符串创建一个计数数组并检查第二个字符串是否具有相同的每个字符计数来轻松完成。
当我们确定可以将 A 转换为 B 时,如何找到最小操作数?这个想法是从两个字符串的最后一个字符开始匹配。如果最后一个字符匹配,那么我们的任务减少到 n-1 个字符。如果最后一个字符不匹配,则在A中找到B的不匹配字符的位置。两个位置之间的差异表明A的这些字符必须移动到A的当前字符之前。

下面是完整的算法。
1) 通过首先为 A 的所有字符创建一个计数数组,然后检查 B 是否对每个字符具有相同的计数,来查找 A 是否可以转换为 B。
2) 将结果初始化为 0。
3) 从两个字符串的末尾开始遍历。
……a) 如果 A 和 B 的当前字符匹配,即 A[i] == B[j]
………那么 i = i-1 和 j = j-1
b) 如果当前字符不匹配,则在剩余字符中搜索 B[j]
………一种。搜索时,随着这些字符不断增加结果
…………必须提前进行 A 到 B 的转换。

下面是基于这个想法的实现。

C++
// C++ program to find minimum number of
// operations required to transform one string to other
#include
using namespace std;
 
// Function to find minimum number of operations required to transform
// A to B.
int minOps(string& A, string& B)
{
    int m = A.length(), n = B.length();
 
     // This parts checks whether conversion is
     // possible or not
    if (n != m)
       return -1;
    int count[256];
    memset(count, 0, sizeof(count));
    for (int i=0; i=0; )
    {
        // If there is a mismatch, then keep incrementing
        // result 'res' until B[j] is not found in A[0..i]
        while (i>=0 && A[i] != B[j])
        {
            i--;
            res++;
        }
 
        // If A[i] and B[j] match
        if (i >= 0)
        {
            i--;
            j--;
        }
    }
    return res;
}
 
// Driver program
int main()
{
    string A = "EACBD";
    string B = "EABCD";
    cout << "Minimum number of operations "
            "required is " << minOps(A, B);
    return 0;
}


Java
// Java program to find minimum number of
// operations required to transform one
// string to other
import java.io.*;
import java.util.*;
 
public class GFG {
     
    // Function to find minimum number of
    // operations required to transform
    // A to B.
    public static int minOps(String A, String B)
    {
         
        // This parts checks whether conversion is
        // possible or not
        if(A.length() != B.length())
            return -1;
         
        int i, j, res = 0;
        int count [] = new int [256];
         
        // count characters in A
         
        // subtract count for every character in B
        for(i = 0; i < A.length(); i++)
        {
            count[A.charAt(i)]++;
            count[B.charAt(i)]--;
        }
         
        // Check if all counts become 0
        for(i = 0; i < 256; i++)
            if(count[i] != 0)
                return -1;
         
        i = A.length() - 1;
        j = B.length() - 1;
 
        while(i >= 0)
        {
            // If there is a mismatch, then
            // keep incrementing result 'res'
            // until B[j] is not found in A[0..i]
            if(A.charAt(i) != B.charAt(j))
                res++;
            else
                j--;
            i--;        
        }
        return res;    
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String A = "EACBD";
        String B = "EABCD";
         
        System.out.println("Minimum number of "
                    + "operations required is "
                                 + minOps(A, B));
    }
}
 
// This code is contributed by Dipesh Jain
// (dipesh_jain)


Python3
# Python program to find the minimum number of
# operations required to transform one string to other
 
# Function to find minimum number of operations required
# to transform A to B
def minOps(A, B):
    m = len(A)
    n = len(B)
 
    # This part checks whether conversion is possible or not
    if n != m:
        return -1
 
    count = [0] * 256
 
    for i in range(n):        # count characters in A
        count[ord(B[i])] += 1
    for i in range(n):        # subtract count for every char in B
        count[ord(A[i])] -= 1
    for i in range(256):    # Check if all counts become 0
        if count[i]:
            return -1
 
    # This part calculates the number of operations required
    res = 0
    i = n-1
    j = n-1   
    while i >= 0:
     
        # if there is a mismatch, then keep incrementing
        # result 'res' until B[j] is not found in A[0..i]
        while i>= 0 and A[i] != B[j]:
            i -= 1
            res += 1
 
        # if A[i] and B[j] match
        if i >= 0:
            i -= 1
            j -= 1
 
    return res
 
# Driver program
A = "EACBD"
B = "EABCD"
print ("Minimum number of operations required is " + str(minOps(A,B)))
# This code is contributed by Bhavya Jain


C#
// C# program to find minimum number of
// operations required to transform one
// string to other
using System;
 
class GFG
{
 
// Function to find minimum number of
// operations required to transform
// A to B.
public static int minOps(string A, string B)
{
 
    // This parts checks whether
    // conversion is possible or not
    if (A.Length != B.Length)
    {
        return -1;
    }
 
    int i, j, res = 0;
    int[] count = new int [256];
 
    // count characters in A
 
    // subtract count for every
    // character in B
    for (i = 0; i < A.Length; i++)
    {
        count[A[i]]++;
        count[B[i]]--;
    }
 
    // Check if all counts become 0
    for (i = 0; i < 256; i++)
    {
        if (count[i] != 0)
        {
            return -1;
        }
    }
 
    i = A.Length - 1;
    j = B.Length - 1;
 
    while (i >= 0)
    {
        // If there is a mismatch, then
        // keep incrementing result 'res'
        // until B[j] is not found in A[0..i]
        if (A[i] != B[j])
        {
            res++;
        }
        else
        {
            j--;
        }
        i--;
    }
    return res;
}
 
// Driver code
public static void Main(string[] args)
{
    string A = "EACBD";
    string B = "EABCD";
 
    Console.WriteLine("Minimum number of " +
                      "operations required is " +
                       minOps(A, B));
}
}
 
// This code is contributed by Shrikant13


PHP
=0; )
    {
        // If there is a mismatch, then keep incrementing
        // result 'res' until B[j] is not found in A[0..i]
        while ($i>=0 && $A[$i] != $B[$j])
        {
            $i--;
            $res++;
        }
  
        // If A[i] and B[j] match
        if ($i >= 0)
        {
            $i--;
            $j--;
        }
    }
    return $res;
}
  
// Driver program
 
$A = "EACBD";
$B = "EABCD";
echo "Minimum number of operations ".
            "required is ". minOps($A, $B);
return 0;
?>


Javascript


输出:

Minimum number of operations required is 3

时间复杂度: O(n),请注意 i 总是递减(在 while 循环和 if 中),for 循环从 n-1 开始并在 i >= 0 时运行。