C语言 Hash版
struct hmap_st {
char key;
int val;
UT_hash_handle hh;
};
bool isIsomorphic(char * s, char * t){
struct hmap_st *hmapa = NULL;
struct hmap_st *hmapb = NULL;
struct hmap_st *ta = NULL;
struct hmap_st *tb = NULL;
int seqa = 0;
int seqb = 0;
if (strlen(s) != strlen(t))
return false;
while(1) {
if(s == NULL || t == NULL) {
if (s == NULL && t == NULL)
return true;
else
return false;
}
if (*s == '\0' || *t == '\0') {
if (*s == '\0' && *t == '\0')
return true;
else
return false;
}
HASH_FIND(hh, hmapa, s, sizeof(ta->key), ta);
if (ta == NULL) {
ta = calloc(1, sizeof(*ta));
ta->key = *s;
ta->val = seqa++;
HASH_ADD(hh, hmapa, key, sizeof(ta->key), ta);
}
HASH_FIND(hh, hmapb, t, sizeof(tb->key), tb);
if (tb == NULL) {
tb = calloc(1, sizeof(*tb));
tb->key = *t;
tb->val = seqb++;
HASH_ADD(hh, hmapb, key, sizeof(tb->key), tb);
}
if (ta->val != tb->val)
return false;
s++;
t++;
}
return true;
}
思路
- 转编码模式,字符串内给字母编码,第一个出现的字符编码为0,第二个为1,以此类推;使用这样的编码模式,分别给不同的字符串数据编码,那么比较编码后是否相同来判断是否同构;
结果

C语言编码版
bool isIsomorphic(char* s, char* t) {
int map_s[256] = {0};
int map_t[256] = {0};
for (int i = 0; s[i] != '\0'; i++) {
if (map_s[s[i]] != map_t[t[i]]) {
return false;
}
map_s[s[i]] = i + 1;
map_t[t[i]] = i + 1;
}
return true;
}
结果

题目
