📌  相关文章
📜  检查是否可以通过交换或替换字符使一个字符串等于另一个字符串

📅  最后修改于: 2021-04-17 15:22:48             🧑  作者: Mango

给定两个字符串S1S2 ,任务是通过交换任意一对字符替换字符串S1中的任何字符来检查字符串S1是否等于字符串S2 。如果可以使字符串S1等于S2 ,则打印“是” 。否则,打印“否”

例子:

方法:解决此问题的想法是找到字符串字符的频率,并检查两个字符串是否使用了相同的字符。请按照以下步骤解决问题:

  • 初始化两个数组a []b []以存储字符串S1S2的频率。
  • 遍历字符串S1S2并将字符串的频率存储在数组a []b []中
  • 对数组a []b []进行排序。
  • 遍历两个数组,如果任何元素在任何索引处都不相等,则打印“否”,因为两个字符串中至少有一个字符不同。
  • 完成上述步骤后,如果不存在不相等的频率,则可以打印“是”,因为可以通过给定的操作将字符串S1转换为字符串S2

以下是此方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find if given strings
// are same or not
bool sameStrings(string str1,
                 string str2)
{
    int N = str1.length();
    int M = str2.length();
 
    // Base Condition
    if (N != M) {
        return false;
    }
 
    // Stores frequency of characters
    // of the string str1 and str2
    int a[256] = { 0 }, b[256] = { 0 };
 
    // Traverse strings str1 & str2 and
    // store frequencies in a[] and b[]
    for (int i = 0; i < N; i++) {
        a[str1[i] - 'a']++;
        b[str2[i] - 'a']++;
    }
 
    // Check if both strings have
    // same characters or not
    int i = 0;
 
    while (i < 256) {
 
        if ((a[i] == 0 && b[i] == 0)
            || (a[i] != 0 && b[i] != 0)) {
            i++;
        }
 
        // If a character is present
        // in one string and is not in
        // another string, return false
        else {
            return false;
        }
    }
 
    // Sort the array a[] and b[]
    sort(a, a + 256);
    sort(b, b + 256);
 
    // Check arrays a and b contain
    // the same frequency or not
    for (int i = 0; i < 256; i++) {
 
        // If the frequencies are not
        // the same after sorting
        if (a[i] != b[i])
            return false;
    }
 
    // At this point, str1 can
    // be converted to str2
    return true;
}
// Driver Code
int main()
{
    string S1 = "cabbba", S2 = "abbccc";
    if (sameStrings(S1, S2))
        cout << "YES" << endl;
    else
        cout << " NO" << endl;
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find if given Strings
// are same or not
static boolean sameStrings(String str1,
                 String str2)
{
    int N = str1.length();
    int M = str2.length();
 
    // Base Condition
    if (N != M)
    {
        return false;
    }
 
    // Stores frequency of characters
    // of the String str1 and str2
    int []a = new int[256];
    int []b = new int[256];
 
    // Traverse Strings str1 & str2 and
    // store frequencies in a[] and b[]
    for (int i = 0; i < N; i++)
    {
        a[str1.charAt(i) - 'a']++;
        b[str2.charAt(i) - 'a']++;
    }
 
    // Check if both Strings have
    // same characters or not
    int i = 0;
    while (i < 256)
    {
        if ((a[i] == 0 && b[i] == 0)
            || (a[i] != 0 && b[i] != 0))
        {
            i++;
        }
 
        // If a character is present
        // in one String and is not in
        // another String, return false
        else
        {
            return false;
        }
    }
 
    // Sort the array a[] and b[]
    Arrays.sort(a);
    Arrays.sort(b);
 
    // Check arrays a and b contain
    // the same frequency or not
    for (i = 0; i < 256; i++)
    {
 
        // If the frequencies are not
        // the same after sorting
        if (a[i] != b[i])
            return false;
    }
 
    // At this point, str1 can
    // be converted to str2
    return true;
}
   
// Driver Code
public static void main(String[] args)
{
    String S1 = "cabbba", S2 = "abbccc";
    if (sameStrings(S1, S2))
        System.out.print("YES" +"\n");
    else
        System.out.print(" NO" +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find if given strings
# are same or not
def sameStrings(str1, str2):
    N = len(str1)
    M = len(str2)
 
    # Base Condition
    if (N != M):
        return False
 
    # Stores frequency of characters
    # of the str1 and str2
    a, b = [0]*256, [0]*256
 
    # Traverse strings str1 & str2 and
    # store frequencies in a[] and b[]
    for i in range(N):
        a[ord(str1[i]) - ord('a')] += 1
        b[ord(str2[i]) - ord('a')] += 1
 
    # Check if both strings have
    # same characters or not
    i = 0
    while (i < 256):
 
        if ((a[i] == 0 and b[i] == 0) or (a[i] != 0 and b[i] != 0)):
            i += 1
 
        # If a character is present
        # in one and is not in
        # another string, return false
        else:
            return False
 
    # Sort the array a[] and b[]
    a = sorted(a)
    b = sorted(b)
 
    # Check arrays a and b contain
    # the same frequency or not
    for i in range(256):
 
        # If the frequencies are not
        # the same after sorting
        if (a[i] != b[i]):
            return False
 
    # At this point, str1 can
    # be converted to str2
    return True
 
  # Driver Code
if __name__ == '__main__':
     
    S1, S2 = "cabbba", "abbccc"
    if (sameStrings(S1, S2)):
        print("YES")
    else:
        print("NO")
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG
{
 
// Function to find if given Strings
// are same or not
static bool sameStrings(string str1,
                 string str2)
{
    int N = str1.Length;
    int M = str2.Length;
 
    // Base Condition
    if (N != M)
    {
        return false;
    }
 
    // Stores frequency of characters
    // of the String str1 and str2
    int []a = new int[256];
    int []b = new int[256];
 
    // Traverse Strings str1 & str2 and
    // store frequencies in a[] and b[]
    for (int j = 0; j < N; j++)
    {
        a[str1[j] - 'a']++;
        b[str2[j] - 'a']++;
    }
 
    // Check if both Strings have
    // same characters or not
    int i = 0 ;
    while (i < 256)
    {
        if ((a[i] == 0 && b[i] == 0)
            || (a[i] != 0 && b[i] != 0))
        {
            i++;
        }
 
        // If a character is present
        // in one String and is not in
        // another String, return false
        else
        {
            return false;
        }
    }
 
    // Sort the array a[] and b[]
    Array.Sort(a);
    Array.Sort(b);
 
    // Check arrays a and b contain
    // the same frequency or not
    for (int j = 0; j < 256; j++)
    {
 
        // If the frequencies are not
        // the same after sorting
        if (a[j] != b[j])
            return false;
    }
 
    // At this point, str1 can
    // be converted to str2
    return true;
}
 
  // Driver Code
  static public void Main()
  {
    string S1 = "cabbba", S2 = "abbccc";
    if (sameStrings(S1, S2))
        Console.Write("YES" +"\n");
    else
        Console.Write(" NO" +"\n");
  }
}
 
// This code is contributed by code_hunt.


输出:
YES

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