Ruby implementation O(n)


  • 2
    F

    A simple ruby implementation. The hash table only need to address the position of the character appeared last time.

    # @param {String} s
    # @param {String} t
    # @return {Boolean}
    def is_isomorphic(s, t)
        # Algorithm: Hash, Loop iterative test and fast fail
        return false if s.length != t.length
        sha, tha = {}, {}
        0.upto(s.length) do |i|
            return false if sha[s[i]] != tha[t[i]]
            sha[s[i]], tha[t[i]] = i, i
        end
        true
    end

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.