Leetcode 161: One Edit Distance

161. One Edit Distance

  • Total Accepted: 20350
  • Total Submissions: 68060
  • Difficulty: Medium
  • Contributors: Admin

Given two strings S and T, determine if they are both one edit distance apart.

 
 
 

Code

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        for idx, (chr_s, chr_t) in enumerate(zip(s, t)):
            if chr_s != chr_t:
                # when s and t have same length, 
                # the only possibility is they only differ at this index 
                if len(s) == len(t):
                    return s[idx+1:] == t[idx+1:]
                # if s is longer than t, the only possibility is 
                # s has an insertion at idx
                elif len(s) > len(t):
                    return s[idx+1:] == t[idx:]
                # otherwise,, the only possibility is t has an insertion
                # at idx
                else:
                    return s[idx:] == t[idx+1:]

        return abs(len(s) - len(t)) == 1

 

Idea

See comments. There are only three conditions to determine if two strings are one edit distance apart.

 

Reference: https://discuss.leetcode.com/topic/30308/my-clear-java-solution-with-explanation

Leave a comment

Your email address will not be published. Required fields are marked *