Ruby solution using a single hash table

  • 0
    # I included a driver which assumes the input is the lone command-line argument,
    # with each line containing the two strings which form one test input
    def is_isomorphic(s, t)
      dict = {}
      # rule 1: each distinct character in s must map to the same character (at the
      # same character position) in t
      0.upto(s.length - 1) do |i|
        if dict.key?(s[i])
          return false if dict[s[i]] != t[i]
          dict[s[i]] = t[i]
      # rule 2: different characters in s must not map to the same character
      # in t.  To detect this, simply check values in hash for duplicates
      return false if dict.values.uniq.length != dict.values.length
      return true
    # Driver main program[0]).each_line do |line|
      next if line.chomp!.empty?
      words = line.split
      puts (is_isomorphic(words[0], words[1]) ? "true" : "false")

Log in to reply

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