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
Example 2:
Input: s = "foo", t = "bar" Output: false
Example 3:
Input: s = "paper", t = "title" Output: true
Solution:
1. 先設定 objectS = {}, objectT = {}。
2. 運用 for 迴圈次數為 s 的長度,每一輪比對內容。
3. 如不同則返回 false
4. 其餘狀況將該輪的 object內容更新。
5. 完整走完迴圈則返回 ture。
Code 1:
var isIsomorphic = function(s, t) { if (s.length !== t.length) return false; 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[2]] = i //2 objectT[t[2]] = i //2 return true
Example 2
Input: s = "foo", t = "bar" 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]] = 1, objectT[t[2]] = underlined //!== return false
Example 3
Input: s = "paper", t = "title" 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]] = 0, objectT[t[2]] = 0 //=== objectS[s[2]] = i //2 objectT[t[2]] = i //2 step.4 i = 3 objectS[s[3]] = underlined, objectT[t[3]] = underlined //=== objectS[s[3]] = i //3 objectT[t[3]] = i //3 step.5 i = 4 objectS[s[4]] = underlined, objectT[t[4]] = underlined //=== objectS[s[4]] = i //4 objectT[t[4]] = i //4 step.6 i = 5 objectS[s[5]] = underlined, objectT[t[5]] = underlined //=== objectS[s[5]] = i //5 objectT[t[5]] = i //5 return true
Code 2:
var isIsomorphic = function(s, t) { if (s.length !== t.length) return false; for (let i = 0; i < s.length; i++) { if (s.indexOf(s[i]) !== t.indexOf(t[i])) { return false; } } return true; };