📌  相关文章
📜  检查给定的字符串可以通过给定的可能交换转换为另一个字符串

📅  最后修改于: 2021-10-28 01:27:35             🧑  作者: Mango

给定两个字符串str1str2 ,任务是通过执行以下操作任意次数来检查字符串str1 是否可以转换为字符串str2

  • 交换str1 的任意两个字符。
  • SWAP str1中字符的所有匹配到str1中任何其他显着的字符的所有地方。

例子:

方法:该问题可以使用贪心技术解决。请按照以下步骤解决问题:

  • 初始化两个数组,比如hash1[256]hash2[256]来分别存储str1str2的每个不同元素的频率。
  • 初始化两个集合,比如st1st2来存储str1str2的不同字符。
  • 遍历字符串并存储str1str2的每个不同字符的频率。
  • hash1[]hash2[]数组进行排序。
  • 如果st1st2不相等,则打印 false。
  • 使用变量i遍历hash1[]hash2[]数组并检查(hash1[i] != hash2[i]) 的值是否为真。如果发现为真,则打印False
  • 否则,打印True

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
bool checkStr1CanConStr2(string& str1,
                         string& str2)
{
    // Stores length of str1
    int N = str1.length();
 
    // Stores length of str2
    int M = str2.length();
 
    // Stores distinct characters
    // of str1
    set st1;
 
    // Stores distinct characters
    // of str2
    set st2;
 
    // Stores frequency of
    // each character of str1
    int hash1[256] = { 0 };
 
    // Traverse the string str1
    for (int i = 0; i < N; i++) {
 
        // Update frequency
        // of str1[i]
        hash1[str1[i]]++;
    }
 
    // Traverse the string str1
    for (int i = 0; i < N; i++) {
 
        // Insert str1[i]
        // into st1
        st1.insert(str1[i]);
    }
 
    // Traverse the string str2
    for (int i = 0; i < M; i++) {
 
        // Insert str1[i]
        // into st1
        st2.insert(str2[i]);
    }
 
    // If distinct characters in
    // str1 and str2 are not same
    if (st1 != st2) {
        return false;
    }
 
    // Stores frequency of
    // each character of str2
    int hash2[256] = { 0 };
 
    // Traverse the string str2
    for (int i = 0; i < M; i++) {
 
        // Update frequency
        // of str2[i]
        hash2[str2[i]]++;
    }
 
    // Sort hash1[] array
    sort(hash1, hash1 + 256);
 
    // Sort hash2[] array
    sort(hash2, hash2 + 256);
 
    // Traverse hash1[] and hash2[]
    for (int i = 0; i < 256; i++) {
 
        // If hash1[i] not
        // equal to hash2[i]
        if (hash1[i] != hash2[i]) {
            return false;
        }
    }
    return true;
}
 
// Driver Code
int main()
{
    string str1 = "xyyzzlll";
    string str2 = "yllzzxxx";
    if (checkStr1CanConStr2(str1, str2)) {
        cout << "True";
    }
    else {
        cout << "False";
    }
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
static boolean checkStr1CanConStr2(String str1,
                         String str2)
{
    // Stores length of str1
    int N = str1.length();
 
    // Stores length of str2
    int M = str2.length();
 
    // Stores distinct characters
    // of str1
    HashSet st1 = new HashSet<>();
 
    // Stores distinct characters
    // of str2
    HashSet st2 =  new  HashSet<>();
 
    // Stores frequency of
    // each character of str1
    int hash1[] = new int[256];
 
    // Traverse the String str1
    for (int i = 0; i < N; i++)
    {
 
        // Update frequency
        // of str1[i]
        hash1[str1.charAt(i)]++;
    }
 
    // Traverse the String str1
    for (int i = 0; i < N; i++)
    {
 
        // Insert str1[i]
        // into st1
        st1.add((int)str1.charAt(i));
    }
 
    // Traverse the String str2
    for (int i = 0; i < M; i++)
    {
 
        // Insert str1[i]
        // into st1
        st2.add((int)str2.charAt(i));
    }
 
    // If distinct characters in
    // str1 and str2 are not same
    if (!st1.equals(st2))
    {
        return false;
    }
 
    // Stores frequency of
    // each character of str2
    int hash2[] = new int[256];
 
    // Traverse the String str2
    for (int i = 0; i < M; i++)
    {
 
        // Update frequency
        // of str2[i]
        hash2[str2.charAt(i)]++;
    }
 
    // Sort hash1[] array
    Arrays.sort(hash1);
 
    // Sort hash2[] array
    Arrays.sort(hash2);
 
    // Traverse hash1[] and hash2[]
    for (int i = 0; i < 256; i++)
    {
 
        // If hash1[i] not
        // equal to hash2[i]
        if (hash1[i] != hash2[i])
        {
            return false;
        }
    }
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    String str1 = "xyyzzlll";
    String str2 = "yllzzxxx";
    if (checkStr1CanConStr2(str1, str2))
    {
        System.out.print("True");
    }
    else
    {
        System.out.print("False");
    }
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
def checkStr1CanConStr2(str1, str2):
 
    # Stores length of str1
    N = len(str1)
 
    # Stores length of str2
    M = len(str2)
 
    # Stores distinct characters
    # of str1
    st1 = set([])
 
    # Stores distinct characters
    # of str2
    st2 = set([])
 
    # Stores frequency of
    # each character of str1
    hash1 = [0] * 256
 
    # Traverse the string str1
    for i in range(N):
 
        # Update frequency
        # of str1[i]
        hash1[ord(str1[i])] += 1
 
    # Traverse the string str1
    for i in range(N):
 
        # Insert str1[i]
        # into st1
        st1.add(str1[i])
 
    # Traverse the string str2
    for i in range(M):
 
        # Insert str1[i]
        # into st1
        st2.add(str2[i])
 
    # If distinct characters in
    # str1 and str2 are not same
    if (st1 != st2):
        return False
 
    # Stores frequency of
    # each character of str2
    hash2 = [0] * 256
 
    # Traverse the string str2
    for i in range(M):
 
        # Update frequency
        # of str2[i]
        hash2[ord(str2[i])] += 1
 
    # Sort hash1[] array
    hash1.sort()
 
    # Sort hash2[] array
    hash2.sort()
 
    # Traverse hash1[] and hash2[]
    for i in range(256):
 
        # If hash1[i] not
        # equal to hash2[i]
        if (hash1[i] != hash2[i]):
            return False
 
    return True
 
# Driver Code
if __name__ == "__main__":
 
    str1 = "xyyzzlll"
    str2 = "yllzzxxx"
     
    if (checkStr1CanConStr2(str1, str2)):
        print("True")
    else:
        print("False")
 
# This code is contributed by chitranayal


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
static bool checkStr1CanConStr2(String str1,
                         String str2)
{
    // Stores length of str1
    int N = str1.Length;
 
    // Stores length of str2
    int M = str2.Length;
 
    // Stores distinct characters
    // of str1
    HashSet st1 = new HashSet();
 
    // Stores distinct characters
    // of str2
    HashSet st2 =  new  HashSet();
 
    // Stores frequency of
    // each character of str1
    int []hash1 = new int[256];
 
    // Traverse the String str1
    for (int i = 0; i < N; i++)
    {
 
        // Update frequency
        // of str1[i]
        hash1[str1[i]]++;
    }
 
    // Traverse the String str1
    for (int i = 0; i < N; i++)
    {
 
        // Insert str1[i]
        // into st1
        st1.Add(str1[i]);
    }
 
    // Traverse the String str2
    for (int i = 0; i < M; i++)
    {
 
        // Insert str1[i]
        // into st1
        st2.Add(str2[i]);
    }
 
    // If distinct characters in
    // str1 and str2 are not same
    if (st1.Equals(st2))
    {
        return false;
    }
 
    // Stores frequency of
    // each character of str2
    int []hash2 = new int[256];
 
    // Traverse the String str2
    for (int i = 0; i < M; i++)
    {
 
        // Update frequency
        // of str2[i]
        hash2[str2[i]]++;
    }
 
    // Sort hash1[] array
    Array.Sort(hash1);
 
    // Sort hash2[] array
    Array.Sort(hash2);
 
    // Traverse hash1[] and hash2[]
    for (int i = 0; i < 256; i++)
    {
 
        // If hash1[i] not
        // equal to hash2[i]
        if (hash1[i] != hash2[i])
        {
            return false;
        }
    }
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str1 = "xyyzzlll";
    String str2 = "yllzzxxx";
    if (checkStr1CanConStr2(str1, str2))
    {
        Console.Write("True");
    }
    else
    {
        Console.Write("False");
    }
}
}
 
 // This code is contributed by 29AjayKumar


Javascript


输出:
True

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程