Compruebe si dos strings se pueden hacer iguales copiando sus caracteres con los adyacentes

Dadas dos strings str1 y str2 , la tarea es verificar si ambas strings pueden igualarse copiando cualquier carácter de la string con su carácter adyacente. Tenga en cuenta que esta operación se puede realizar cualquier número de veces.
Ejemplos: 
 

Entrada: str1 = «abc», str2 = «def» 
Salida: No 
Como todos los caracteres en ambas strings son diferentes. 
Por lo tanto, no hay forma de que puedan ser iguales.
Entrada: str1 = “abc”, str2 = “fac” 
Salida: Sí 
str1 = “abc” -> “aac” 
str2 = “fac” -> “aac” 
 

Enfoque: para que las strings sean iguales a la operación dada, deben tener la misma longitud y debe haber al menos un carácter que sea común en ambas strings. Para verificar eso, cree una array de frecuencia freq[] que almacenará la frecuencia de todos los caracteres de str1 y luego para cada carácter de str2 si su frecuencia en str1 es mayor que 0 , entonces es posible hacer que ambas strings sean iguales.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 26
 
// Function that returns true if both
// the strings can be made equal
// with the given operation
bool canBeMadeEqual(string str1, string str2)
{
    int len1 = str1.length();
    int len2 = str2.length();
 
    // Lengths of both the strings
    // have to be equal
    if (len1 == len2) {
 
        // To store the frequency of the
        // characters of str1
        int freq[MAX];
        for (int i = 0; i < len1; i++) {
            freq[str1[i] - 'a']++;
        }
 
        // For every character of str2
        for (int i = 0; i < len2; i++) {
 
            // If current character of str2
            // also appears in str1
            if (freq[str2[i] - 'a'] > 0)
                return true;
        }
    }
 
    return false;
}
 
// Driver code
int main()
{
    string str1 = "abc", str2 = "defa";
 
    if (canBeMadeEqual(str1, str2))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

Java

// Java implementation of the above approach
class GFG
{
    static int MAX = 26;
     
    // Function that returns true if both
    // the strings can be made equal
    // with the given operation
    static boolean canBeMadeEqual(String str1,
                                  String str2)
    {
        int len1 = str1.length();
        int len2 = str2.length();
     
        // Lengths of both the strings
        // have to be equal
        if (len1 == len2)
        {
     
            // To store the frequency of the
            // characters of str1
            int freq[] = new int[MAX];
             
            for (int i = 0; i < len1; i++)
            {
                freq[str1.charAt(i) - 'a']++;
            }
     
            // For every character of str2
            for (int i = 0; i < len2; i++)
            {
     
                // If current character of str2
                // also appears in str1
                if (freq[str2.charAt(i) - 'a'] > 0)
                    return true;
            }
        }
        return false;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String str1 = "abc", str2 = "defa";
     
        if (canBeMadeEqual(str1, str2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by AnkitRai01

Python3

# Python3 implementation of the approach
MAX = 26
 
# Function that returns true if both
# the strings can be made equal
# with the given operation
def canBeMadeEqual(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
 
    # Lengths of both the strings
    # have to be equal
    if (len1 == len2):
 
        # To store the frequency of the
        # characters of str1
        freq = [0 for i in range(MAX)]
        for i in range(len1):
            freq[ord(str1[i]) - ord('a')] += 1
 
        # For every character of str2
        for i in range(len2):
 
            # If current character of str2
            # also appears in str1
            if (freq[ord(str2[i]) - ord('a')] > 0):
                return True
 
    return False
 
# Driver code
str1 = "abc"
str2 = "defa"
 
if (canBeMadeEqual(str1, str2)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by Mohit Kumar

C#

// C# implementation of the above approach
using System;
 
class GFG
{
    static int MAX = 26;
     
    // Function that returns true if both
    // the strings can be made equal
    // with the given operation
    static Boolean canBeMadeEqual(String str1,
                                   String str2)
    {
        int len1 = str1.Length;
        int len2 = str2.Length;
     
        // Lengths of both the strings
        // have to be equal
        if (len1 == len2)
        {
     
            // To store the frequency of the
            // characters of str1
            int []freq = new int[MAX];
             
            for (int i = 0; i < len1; i++)
            {
                freq[str1[i] - 'a']++;
            }
     
            // For every character of str2
            for (int i = 0; i < len2; i++)
            {
     
                // If current character of str2
                // also appears in str1
                if (freq[str2[i] - 'a'] > 0)
                    return true;
            }
        }
        return false;
    }
     
    // Driver code
    public static void Main (String []args)
    {
        String str1 = "abc", str2 = "defa";
     
        if (canBeMadeEqual(str1, str2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by Arnab Kundu

Javascript

<script>
 
    // JavaScript implementation of the above approach
     
    let MAX = 26;
       
    // Function that returns true if both
    // the strings can be made equal
    // with the given operation
    function canBeMadeEqual(str1, str2)
    {
        let len1 = str1.length;
        let len2 = str2.length;
       
        // Lengths of both the strings
        // have to be equal
        if (len1 == len2)
        {
       
            // To store the frequency of the
            // characters of str1
            let freq = new Array(MAX);
            freq.fill(0);
               
            for (let i = 0; i < len1; i++)
            {
                freq[str1[i].charCodeAt() -
                'a'.charCodeAt()]++;
            }
       
            // For every character of str2
            for (let i = 0; i < len2; i++)
            {
       
                // If current character of str2
                // also appears in str1
                if (freq[str2[i].charCodeAt() -
                'a'.charCodeAt()] > 0)
                    return true;
            }
        }
        return false;
    }
     
    let str1 = "abc", str2 = "defa";
       
    if (canBeMadeEqual(str1, str2))
      document.write("Yes");
    else
      document.write("No");
             
</script>
Producción: 

No

 

Complejidad de tiempo: O(N)

Espacio Auxiliar: O(26)

Publicación traducida automáticamente

Artículo escrito por Akshita207 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *