LeetCode Js-205. Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings s and t 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.
給予兩個字串 s 和 t,確認他們是否同構。
如果可以交換 s 和 t,則兩個字串為同構。
當保持字符順序時,必須替換所有出現的字符。
兩個字符不可對應到一個字符,但是可以對應到自己。
Example 1:
Input: s = "egg", t = "add"
Output: true
Solution:
Code:
var isIsomorphic = function(s, t) {
let objectS = {}, objectT = {}
for (let i = 0; i < s.length; i++) {
if (objectS[s[i]] !== objectT[t[i]]) {
return false
} else {
objectS[s[i]] = i
objectT[t[i]] = i
}
}
return true
}
FlowChart:
Example 1
Input: s = "egg", t = "add"
step.1
i = 0
objectS[s[0]] = underlined, objectT[t[0]] = underlined //===
objectS[s[0]] = i //0
objectT[t[0]] = i //0
step.2
i = 1
objectS[s[1]] = underlined, objectT[t[1]] = underlined //===
objectS[s[1]] = i //1
objectT[t[1]] = i //1
step.3
i = 2
objectS[s[2]] = underlined, objectT[t[2]] = underlined //===
objectS[s[1]] = i //2
objectT[t[1]] = i //2
return true