1. 程式人生 > 其它 >【力扣-簡單】205. 同構字串

【力扣-簡單】205. 同構字串

技術標籤:leecode字串leetcode

給定兩個字串s和t,判斷它們是否是同構的。
如果s中的字元可以被替換得到t,那麼這兩個字串是同構的。
所有出現的字元都必須用另一個字元替換,同時保留字元的順序。兩個字元不能對映到同一個字元上,但字元可以對映自己本身。

示例 1:

輸入: s = "egg", t = "add"
輸出: true
示例 2:

輸入: s = "foo", t = "bar"
輸出: false
示例 3:

輸入: s = "paper", t = "title"

輸出: true
說明:
你可以假設s和 t 具有相同的長度。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/isomorphic-strings

【解答】

bool isIsomorphic(string s, string t) {
        int size = s.size();
        if (size != t.size()) return false;
        int type = 0, sCount[128] = {0}, tCount[128] = {0};
        for(int i = 0; i < size; i++){
            int sCh = s[i], tCh = t[i];
            if (sCount[sCh] == 0 && tCount[tCh] == 0){
                type++;
                sCount[sCh] = type;
                tCount[tCh] = type;
            }else if (sCount[sCh] != tCount[tCh]){
                    return false;
            }
        }
        return true;
    }