📌  相关文章
📜  C 程序检查两个给定的字符串是否彼此同构

📅  最后修改于: 2021-09-04 07:54:53             🧑  作者: Mango

给定两个字符串str1str2 ,任务是检查两个给定的字符串是否彼此同构。

例子:

Hashing 方法:请参阅上一篇关于基于 Hashmap 的方法的文章。
时间复杂度: O(N)
辅助空间: O(256)

基于 ASCII 值的方法:其思想与上述方法类似。请按照以下步骤解决问题:

  1. 初始化两个大小为 256 的数组。
  2. 迭代通过给定字符串和增量索引的字符等于所述字符的ASCII值在i位置。
  3. 如果字符映射没有冲突,则打印Yes 。否则,打印No

下面是上述方法的实现:

C
// C Program to implement
// the above approach
  
#include 
#include 
#include 
  
// Function to check and return if strings
// str1 and str2 are ismorphic
bool areIsomorphic(char *str1, char *str2)
{
    // If the length of the strings
    // are not equal
    if (strlen(str1) != strlen(str2)) {
        return false;
    }
  
    // Initialise two arrays
    int arr1[256] = { 0 }, arr2[256] = { 0 };
  
    // Travsersing both the strings
    for (int i = 0; i < strlen(str1); i++) {
  
        // If current characters don't map
        if (arr1[(int)str1[i]] 
        != arr2[(int)str2[i]]) {
            return false;
        }
  
        // Increment the count of characters
        // at their respective ASCII indices
        arr1[(int)str1[i]]++;
        arr2[(int)str2[i]]++;
    }
    return true;
}
  
// Driver Code
int main()
{
    char s1[] = "aab", s2[] = "xxy";
  
    if (areIsomorphic(s1, s2))
        printf("Yes\n");
    else
        printf("No\n");
  
    return 0;
}


输出:
Yes

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live