Isomorphic Strings

来源:互联网 发布:php get获取json数据 编辑:程序博客网 时间:2024/05/01 19:28

同构字符串,刚开始还没读懂题目。。。逻辑不难,用string a依次映射字符到string b,不过刚开始我是没想到的,一直在想分别将a和b映射到数组里边。这题也说明了哈希表的运用是很灵活的,要根据实际情况选择映射方法。另一个难点在还得从b映射到a检查一次,因为映射是单向的,只能检测发射方的字符排列,接收方是无法判断的,因此需要掉一个头再判断一次。例如“foo”“bar”可以单向判断,但“ab”“aa”就不行了。

代码如下:

bool isomoHash(char c, char *hashmap, char c2) {    int index = 0;    index = c;    if (index < 0)        index = c - 'A';    if (*(hashmap + index) == 0) {        *(hashmap + index) = c2;        return true;    }    else if (*(hashmap + index) == c2)        return true;    else        return false;}bool isIsomorphic(char* s, char* t) {    bool result = true;    int n = 256;    char *hashmap = (char *)malloc(sizeof(char) * n);    char *hashmap2 = (char *)malloc(sizeof(char) * n);    memset(hashmap, 0, sizeof(char) * n);    memset(hashmap2, 0, sizeof(char) * n);        while (*s != 0) {        if (!isomoHash(*s, hashmap, *t)) {            result = false;            break;        }        // if (!isomoHash(*t, hashmap2, *s)) {        //     result = false;        //     break;        // }        s++, t++;    }        free(hashmap);    free(hashmap2);    return result;}


0 0
原创粉丝点击