Sponsored
Sponsored
This approach involves using two hash maps (or dictionaries) to track the character mappings from string s to string t and vice versa. We iterate over the characters of both strings and update the mappings. If at any point the expected character mapping does not match, we conclude that the strings are not isomorphic.
Time Complexity: O(n) where n is the length of the strings (which are equal).
Space Complexity: O(1), as the size of the map is constant (256 character ASCII set).
1#include <stdbool.h>
2#include <string.h>
3
4bool isIsomorphic(char * s, char * t) {
5 int map_s[256] = {0};
6 int map_t[256] = {0};
7 int len = strlen(s);
8 for (int i = 0; i < len; i++) {
9 if (map_s[s[i]] != map_t[t[i]]) {
10 return false;
11 }
12 map_s[s[i]] = map_t[t[i]] = i + 1;
13 }
14 return true;
15}
Using arrays indexed by ASCII values, we map each character from string s to string t and vice versa. We increment the indices compared by one to differentiate from default values. If a mismatch is found during comparison, we return false immediately.
Generate a unique pattern for each string by numbering the characters according to their first appearance. Compare character patterns of the two strings. If the patterns match, the strings are isomorphic.
Time Complexity: O(n), due to single-pass traversal for number pattern generation.
Space Complexity: O(1), as the pattern size remains constant with 256 ASCII values.
1function
In JavaScript, simulate generating numeral patterns for input strings for detecting isomorphic cases by character hashing and comparison.