Simple and easy to read Ruby Solution


  • 0
    T

    There are two possibilities:

    1. it's a replacement
    2. it's a deletion

    First find the bigger string, then loop through the characters to find the diff.
    Once a diff has been found, determine which case it is and check to see if the rest of the substring matches.

    # @param {String} s
    # @param {String} t
    # @return {Boolean}
    def is_one_edit_distance(s, t)
      return false if (s.length - t.length).abs > 1
      s, t = t, s if t.length > s.length
      (0...s.length).each do |i|
        next if s[i] == t[i]
        return s[(i+1)..-1] == t[(i+1)..-1] if s.length == t.length
        return s[(i+1)..-1] == t[i..-1]
      end
      return false
    end
    

Log in to reply
 

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