同構字符串 題目 說明: 解題思路 法一 哈希表 字符串indexOf

題目

難度級別:簡單

給定兩個字符串 s 和 t,判斷它們是否是同構的。

如果 s 中的字符可以被替換得到 t ,那麼這兩個字符串是同構的。

所有出現的字符都必須用另一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符可以映射自己本身。

示例 1:

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

示例 2:

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

示例 3:

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

說明:

你可以假設 s 和 t 具有相同的長度。

解題思路

法一

通過固定遍歷字符串末項,且設置一個指針,倒序遍歷,若發現s與t字符串同時與prev項相等,則重新拼接字符串,去掉prev項。若其中一個與prev相等則返回false。遍歷完之後刪除末項。

const isIsomorphic = function(s, t) {
    while(s.length) {
        let prev = s.length - 2

        while(prev >= 0) {
            if (s[s.length - 1] === s[prev] && t[t.length - 1] === t[prev]){
                s = s.slice(0, prev) + s.slice(prev + 1)
                t = t.slice(0, prev) + t.slice(prev + 1)
            }else if (s[s.length - 1] === s[prev] || t[t.length - 1] === t[prev]) {
                return false
            }
            --prev
        }
        s = s.slice(0, s.length - 1)
        t = t.slice(0, t.length - 1)
    }

    return true
};

哈希表

遍歷字符串,2張哈希表分別存儲s與t,若值不存在,存儲值爲索引,若值存在判斷是否相等。

const isIsomorphic = function(s, t) {
    const hashMapS = new Map()
    const hashMapT = new Map()

    for (let i = 0; i < s.length; i++) {
        const hasS = hashMapS.has(s[i])
        const hasT = hashMapT.has(t[i])

        if (!hasS && !hasT) {
            hashMapS.set(s[i], i)
            hashMapT.set(t[i], i)
        }else if(!hasS || !hasT || hashMapS.get(s[i]) !== hashMapT.get(t[i])) {
             return false
        }
    }

    return true
};

字符串indexOf

通過字符串indexOf方法查找與當前項值相等的第一項。若s與t返回的索引不相等,則返回false。

const isIsomorphic = function(s, t) {
    for (let i = 0; i < s.length; i++) {
        if(s.indexOf(s[i]) !== t.indexOf(t[i])) return false
    }
    return true
};

題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/isomorphic-strings

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章