iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
自我挑戰組

JavaScript - 30天 - 自學挑戰系列 第 25

LeetCode Js-205. Isomorphic Strings

  • 分享至 

  • xImage
  •  

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:

  1. 先設定 objectS = {}, objectT = {}。
  2. 運用 for 迴圈次數為 s 的長度,每一輪比對內容。
  3. 如不同則返回 false
  4. 其餘狀況將該輪的 object內容更新。
  5. 完整走完迴圈則返回 ture。

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

上一篇
LeetCode Js-136. Single Number
下一篇
LeetCode Js-724. Find Pivot Index
系列文
JavaScript - 30天 - 自學挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言