205. Isomorphic Strings

Leetcode

https://leetcode.com/problems/reverse-words-in-a-string/

題目

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.

解答

  • 方法一

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

Runtime: 116 ms, faster than 36.06% of JavaScript online submissions for Isomorphic Strings.

Memory Usage: 41.2 MB, less than 44.34% of JavaScript online submissions for Isomorphic Strings.

測資

let s = "egg", t = "add";
s = "foo", t = "bar";
s = "paper", t = "title";

console.log(isIsomorphic(s, t));

Last updated

Was this helpful?