Ruby version solution.


  • 0
    H
    # @param {String} s
    # @param {String} t
    # @return {Boolean}
    def is_isomorphic(s, t)
        if(s.size != t.size)
            return false
        end
        h1 = Hash.new
        h2 = Hash.new
        (0..s.size).each do |i|
            c1 = s[i]
            c2 = t[i]
            if(h1[c1].nil?)
                h1[c1] = c2 
            elsif (h1[c1]!=c2)
                return false
            end
            
            if(h2[c2].nil?)
                h2[c2] = c1 
            elsif (h2[c2]!=c1)
                return false
            end
        end
        return true
    end
    

    Use Hash to improve the time, it takes only O(n), but extra space for Hashing.


  • 0
    R
    def cmp(s, t)
      s_a, t_a = s.split(//), t.split(//)
      diff = s_a.zip(t_a).map { |j, k| j.ord - k.ord }
      cache = {}
      len = s.length
      for c,v in s_a.zip(diff)
        cache[c] ||= v
        return false if cache[c] != v
      end
      return true
    end
    
    # @param {String} s
    # @param {String} t
    # @return {Boolean}
    def is_isomorphic(s, t)
      cmp(s, t) and cmp(t, s)
    end
    

Log in to reply
 

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