C Program to check if two given strings are isomorphic to each other
Last Updated :
19 Aug, 2022
Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not.
Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 map to same character in str2.
Examples:
Input: str1 = “egg”, str2 = “add”
Output: Yes
Explanation:
‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97.
‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100.
Input: str1 = “eggs”, str2 = “add”
Output: No
Hashing Approach: Refer to the previous post for the Hashmap based approach.
Time Complexity: O(N)
Auxiliary Space: O(256)
ASCII-value based Approach: The idea is similar to that of the above approach. Follow the steps below to solve the problem:
- Initialize two arrays of size 256.
- Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.
- If there are no conflicts in the mapping of the characters, print Yes. Otherwise, print No.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool areIsomorphic( char *str1, char *str2)
{
if ( strlen (str1) != strlen (str2)) {
return false ;
}
int arr1[256] = { 0 }, arr2[256] = { 0 };
for ( int i = 0; i < strlen (str1); i++) {
if (arr1[( int )str1[i]]
!= arr2[( int )str2[i]]) {
return false ;
}
arr1[( int )str1[i]]++;
arr2[( int )str2[i]]++;
}
return true ;
}
int main()
{
char s1[] = "aab" , s2[] = "xxy" ;
if (areIsomorphic(s1, s2))
printf ( "Yes\n" );
else
printf ( "No\n" );
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(256)
Share your thoughts in the comments
Please Login to comment...