# 205. Isomorphic Strings

lookup thing,看清楚題目限制 / 記得命名要有意義的

LeetCode

Given two strings s and t, determine if they are isomorphic.

Two strings 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.

input: 兩個 string
output: 找出是否對應
xample 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

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isIsomorphic = function(s, t) {}

Edge Case

  • s = "ab", t="aa"

  • s="aa", t="ab"

如何解

一開始用 map 解,後癌發現有一個限制是 以下,所以除了 key 是唯一,連 value 也要是唯一

No two characters may map to the same character

Code

var isIsomorphic = function(s, t) {
 let lookupS = {};
   let lookupT = {}
   for(let i = 0; i< s.length; i++){
    // didn't have this key before then add
    if(!lookupS[s[i]] && !lookupT[t[i]]){
      lookupS[s[i]] = t[i];
      lookupT[t[i]] = s[i];
    }else{
      if(lookupS[s[i]] !== t[i]){
        return false
      }
    }
   }
    return true;
};

Last updated