How to check if two strings are isomorphic in C

2 Answers

0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool areIsomorphic(const char *s, const char *t) {
    if (strlen(s) != strlen(t)) return false;

    // Arrays to store mapping from s → t and t → s
    int mapST[256] = {0};
    int mapTS[256] = {0};

    for (size_t i = 0; s[i] && t[i]; i++) {
        unsigned char c1 = (unsigned char)s[i];
        unsigned char c2 = (unsigned char)t[i];

        if (mapST[c1] != mapTS[c2]) return false;

        // Store the index + 1 (so that 0 means "not mapped yet")
        mapST[c1] = i + 1;
        mapTS[c2] = i + 1;
    }
    
    return true;
}

int main(void) {
    printf("%d\n", areIsomorphic("egg", "add"));     
    printf("%d\n", areIsomorphic("foo", "bar"));     
    printf("%d\n", areIsomorphic("paper", "title"));
}


/*
run:

true
false
true

*/

 



answered Dec 18, 2025 by avibootz
edited Dec 19, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool areIsomorphic(const char *s, const char *t) {
    if (strlen(s) != strlen(t)) return false;

    // Arrays to store mapping from s → t and t → s
    int mapST[256] = {0};
    int mapTS[256] = {0};

    for (size_t i = 0; s[i] && t[i]; i++) {
        unsigned char c1 = (unsigned char)s[i];
        unsigned char c2 = (unsigned char)t[i];
        if (mapST[c1] != mapTS[c2]) {
            printf("(if) mapST[c1] = %d mapTS[c2] = %d\n", mapST[c1], mapTS[c2]);
            return false;
        }

        // Store the index + 1 (so that 0 means "not mapped yet")
        mapST[c1] = i + 1;
        mapTS[c2] = i + 1;
        printf("c1 = %c c2 = %c - ", c1, c2); 
        printf("mapST[c1] = %d mapTS[c2] = %d\n", mapST[c1], mapTS[c2]);

    }
    
    return true;
}

int main(void) {
    printf("%d\n", areIsomorphic("egg", "add"));     
    printf("%d\n", areIsomorphic("foo", "bar"));     
    printf("%d\n", areIsomorphic("paper", "title"));
}


/*
run:

c1 = e c2 = a - mapST[c1] = 1 mapTS[c2] = 1
c1 = g c2 = d - mapST[c1] = 2 mapTS[c2] = 2
c1 = g c2 = d - mapST[c1] = 3 mapTS[c2] = 3
1
c1 = f c2 = b - mapST[c1] = 1 mapTS[c2] = 1
c1 = o c2 = a - mapST[c1] = 2 mapTS[c2] = 2
(if) mapST[c1] = 2 mapTS[c2] = 0
0
c1 = p c2 = t - mapST[c1] = 1 mapTS[c2] = 1
c1 = a c2 = i - mapST[c1] = 2 mapTS[c2] = 2
c1 = p c2 = t - mapST[c1] = 3 mapTS[c2] = 3
c1 = e c2 = l - mapST[c1] = 4 mapTS[c2] = 4
c1 = r c2 = e - mapST[c1] = 5 mapTS[c2] = 5
1

*/

 



answered Dec 18, 2025 by avibootz
edited Dec 18, 2025 by avibootz
...