205. Isomorphic Strings

1.描述

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.

2.分析

3.代码

bool isIsomorphic(char* s, char* t) {
    if (strlen(s) != strlen(t)) return false;
    if (0 == strlen(s) || 0 == strlen(t)) return true;
    char mapS2T[256];
    char mapT2S[256];
    memset(mapS2T, 0, 256 * sizeof(char));
    memset(mapT2S, 0, 256 * sizeof(char));
    unsigned int len = strlen(s);
    for (unsigned int i = 0; i < len; ++i) {
        if (0 == mapS2T[s[i]] && 0 == mapT2S[t[i]]) {
            mapS2T[s[i]] = t[i];
            mapT2S[t[i]] = s[i];
        } else if (mapS2T[s[i]] != t[i] || mapT2S[t[i]] != s[i])
            return false;
    }
    return true;
}

你可能感兴趣的:(205. Isomorphic Strings)