📌  相关文章
📜  检查一个字符串可以转换为另一字符串

📅  最后修改于: 2021-04-23 21:31:30             🧑  作者: Mango

给定两个字符串strstr1 ,任务是检查是否可以使用以下操作将一个字符串转换为另一个字符串:

  • 用一个不同的字符转换一个字符的所有存在。

例如,如果str =“ abacd”,并且操作是将字符“ a”更改为“ k”,则结果str =“ kbkcd”

例子:

方法:

  • 根据给定的操作,每个唯一字符应映射到一个唯一字符,可以相同或不同。
  • Hashmap可以轻松地对此进行检查。
  • 但是,如果映射中存在一个循环并且无法确定特定顺序,则此操作将失败。
  • 这种情况的一个示例是上面的示例2
  • 因此,对于映射,第一个和最后一个字符作为边缘存储在哈希图中。
  • 为了找到带有边缘的循环,将这些边缘一一映射到父对象,并使用联合和查找算法检查循环。

下面是上述方法的实现。

CPP
// C++ implementation of the above approach.
#include 
using namespace std;
int parent[26];
// Function for find
// from Disjoint set algorithm
int find(int x)
{
    if (x != parent[x])
        return parent[x] = find(parent[x]);
    return x;
}
  
// Function for the union
// from Disjoint set algorithm
void join(int x, int y)
{
    int px = find(x);
    int pz = find(y);
    if (px != pz) {
        parent[pz] = px;
    }
}
// Function to check if one string
// can be converted to another.
bool convertible(string s1, string s2)
{
    // All the characters are checked whether
    // it's either not replaced or replaced
    // by a similar character using a map.
    map mp;
  
    for (int i = 0; i < s1.size(); i++) {
        if (mp.find(s1[i] - 'a') == mp.end()) {
            mp[s1[i] - 'a'] = s2[i] - 'a';
        }
        else {
            if (mp[s1[i] - 'a'] != s2[i] - 'a')
                return false;
        }
    }
    // To check if there are cycles.
    // If yes, then they are not convertible.
    // Else, they are convertible.
    for (auto it : mp) {
        if (it.first == it.second)
            continue;
        else {
            if (find(it.first) == find(it.second))
                return false;
            else
                join(it.first, it.second);
        }
    }
    return true;
}
  
// Function to initialize parent array
// for union and find algorithm.
void initialize()
{
    for (int i = 0; i < 26; i++) {
        parent[i] = i;
    }
}
// Driver code
int main()
{
    // Your C++ Code
    string s1, s2;
    s1 = "abbcaa";
    s2 = "bccdbb";
    initialize();
    if (convertible(s1, s2))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


Java
// Java implementation of the above approach.
import java.util.*;
  
class GFG
{
      
static int []parent = new int[26];
  
// Function for find
// from Disjoint set algorithm
static int find(int x)
{
    if (x != parent[x])
        return parent[x] = find(parent[x]);
    return x;
}
  
// Function for the union
// from Disjoint set algorithm
static void join(int x, int y)
{
    int px = find(x);
    int pz = find(y);
    if (px != pz)
    {
        parent[pz] = px;
    }
}
// Function to check if one String
// can be converted to another.
static boolean convertible(String s1, String s2)
{
    // All the characters are checked whether
    // it's either not replaced or replaced
    // by a similar character using a map.
    HashMap mp = new HashMap();
  
    for (int i = 0; i < s1.length(); i++) 
    {
        if (!mp.containsKey(s1.charAt(i) - 'a'))
        {
            mp.put(s1.charAt(i) - 'a', s2.charAt(i) - 'a');
        }
        else
        {
            if (mp.get(s1.charAt(i) - 'a') != s2.charAt(i) - 'a')
                return false;
        }
    }
      
    // To check if there are cycles.
    // If yes, then they are not convertible.
    // Else, they are convertible.
    for (Map.Entry it : mp.entrySet())
    {
        if (it.getKey() == it.getValue())
            continue;
        else
        {
            if (find(it.getKey()) == find(it.getValue()))
                return false;
            else
                join(it.getKey(), it.getValue());
        }
    }
    return true;
}
  
// Function to initialize parent array
// for union and find algorithm.
static void initialize()
{
    for (int i = 0; i < 26; i++) 
    {
        parent[i] = i;
    }
}
  
// Driver code
public static void main(String[] args)
{
      
    String s1, s2;
    s1 = "abbcaa";
    s2 = "bccdbb";
    initialize();
    if (convertible(s1, s2))
        System.out.print("Yes" + "\n");
    else
        System.out.print("No" + "\n");
}
}
  
// This code is contributed by 29AjayKumar


Python
# Python3 implementation of the above approach.
parent = [0] * 256
  
# Function for find
# from Disjoset algorithm
def find(x):
    if (x != parent[x]):
        parent[x] = find(parent[x])
        return parent[x]
    return x
  
# Function for the union
# from Disjoset algorithm
def join(x, y):
    px = find(x)
    pz = find(y)
    if (px != pz):
        parent[pz] = px
  
# Function to check if one string
# can be converted to another.
def convertible(s1, s2):
      
    # All the characters are checked whether
    # it's either not replaced or replaced
    # by a similar character using a map.
    mp = dict()
  
    for i in range(len(s1)):
        if (s1[i] in mp):
            mp[s1[i]] = s2[i]
        else:
            if s1[i] in mp and mp[s1[i]] != s2[i]:
                return False
      
    # To check if there are cycles.
    # If yes, then they are not convertible.
    # Else, they are convertible.
    for it in mp:
        if (it == mp[it]):
            continue
        else :
            if (find(ord(it)) == find(ord(it))):
                return False
            else:
                join(ord(it), ord(it))
  
    return True
  
# Function to initialize parent array
# for union and find algorithm.
def initialize():
    for i in range(256):
        parent[i] = i
  
# Driver code
s1 = "abbcaa"
s2 = "bccdbb"
initialize()
if (convertible(s1, s2)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach.
using System;
using System.Collections.Generic;
  
class GFG
{
      
static int []parent = new int[26];
  
// Function for find
// from Disjoint set algorithm
static int find(int x)
{
    if (x != parent[x])
        return parent[x] = find(parent[x]);
    return x;
}
  
// Function for the union
// from Disjoint set algorithm
static void join(int x, int y)
{
    int px = find(x);
    int pz = find(y);
    if (px != pz)
    {
        parent[pz] = px;
    }
}
  
// Function to check if one String
// can be converted to another.
static bool convertible(String s1, String s2)
{
    // All the characters are checked whether
    // it's either not replaced or replaced
    // by a similar character using a map.
    Dictionary mp = new Dictionary();
  
    for (int i = 0; i < s1.Length; i++) 
    {
        if (!mp.ContainsKey(s1[i] - 'a'))
        {
            mp.Add(s1[i] - 'a', s2[i] - 'a');
        }
        else
        {
            if (mp[s1[i] - 'a'] != s2[i] - 'a')
                return false;
        }
    }
      
    // To check if there are cycles.
    // If yes, then they are not convertible.
    // Else, they are convertible.
    foreach(KeyValuePair it in mp)
    {
        if (it.Key == it.Value)
            continue;
        else
        {
            if (find(it.Key) == find(it.Value))
                return false;
            else
                join(it.Key, it.Value);
        }
    }
    return true;
}
  
// Function to initialize parent array
// for union and find algorithm.
static void initialize()
{
    for (int i = 0; i < 26; i++) 
    {
        parent[i] = i;
    }
}
  
// Driver code
public static void Main(String[] args)
{
      
    String s1, s2;
    s1 = "abbcaa";
    s2 = "bccdbb";
    initialize();
    if (convertible(s1, s2))
        Console.Write("Yes" + "\n");
    else
        Console.Write("No" + "\n");
}
}
  
// This code is contributed by PrinciRaj1992


输出:
Yes