在這題我們需要判斷兩個字串 s 和 t 是否是 isomorphic。
題目:
s 中每個字元能唯一映射到 t 的某個字元。t 中的每個字元也只能唯一映射回 s 中的某個字元。如果 s 跟 t 可以映射到同一種關係上的話,那表示 s 與 t 為 isomorphic,
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if (s.size() != t.size())
            return false;
        int scount = 0;
        int tcount = 0;
        unordered_map<char, int> smap;
        unordered_map<char, int> tmap;
        string smapstr;
        string tmapstr;
        for (int i = 0; i < s.size(); i++) {
            if (!smap.count(s[i])) {
                smap[s[i]] = scount;
                scount++;
            }
            smapstr += smap[s[i]];
            if (!tmap.count(t[i])) {
                tmap[t[i]] = tcount;
                tcount++;
            }
            tmapstr += tmap[t[i]];
        }
        return smapstr == tmapstr;
    }
};
後來發現可以優化空間複雜度,省去兩個 string 的開銷,因為是按順序,所以有不一樣的就提前回傳 fasle,否則直到最後就是一樣 return true。
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if (s.size() != t.size())
            return false;
        int scount = 0;
        int tcount = 0;
        unordered_map<char, int> smap;
        unordered_map<char, int> tmap;
        for (int i = 0; i < s.size(); i++) {
            if (!smap.count(s[i])) {
                smap[s[i]] = scount;
                scount++;
            }
            if (!tmap.count(t[i])) {
                tmap[t[i]] = tcount;
                tcount++;
            }
            if (smap[s[i]] != tmap[t[i]])
                return false;
        }
        return true;
    }
};
也可以用雙映射的方式,從 s 映射到 t 的,從 t 映射到 s ,來判斷是不是 isomorphic。