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

📅  最后修改于: 2021-10-25 08:19:27             🧑  作者: Mango

鉴于两个字符串S1S2,任务是检查字符串S1可以通过交换任何一对字符替换字符串S1任何字符等于作出字符串S。如果可以使字符串S1等于S2 ,则打印“是” 。否则,打印“否”

例子:

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

  • 初始化两个数组a[]b[]以存储字符串S1S2的频率。
  • 遍历字符串S1S2并将字符串的频率存储在数组a[]b[] 中
  • 对数组a[]b[] 进行排序。
  • 遍历这两个阵列,并且如果任何元件是在任何索引不相等的,然后打印“否”,因为至少有一个字符,该字符在两个字符串不同。
  • 在上述步骤之后,如果不存在任何不等频率,则打印“Yes”,因为字符串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.


Javascript


输出:
YES

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

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