Given two strings S and T, determine if they are both one edit distance apart.
One edit distance means that two strings will be identical by either one update, delete, or add operation.
The Idea: This is the type of problem that is fairly simple, but can easily get messy. I've added comments below in the code explains all cases that can happen.
Complexity: O(n) time and O(1) space
classSolution(object):defisOneEditDistance(self,s,t):""" :type s: str :type t: str :rtype: bool """ s_larger =len(s)>=len(t) t_larger =len(s)<=len(t)for i inrange(min(len(s), len(t))):if s[i]!= t[i]:# cases:# 1. if both are the same length, then both# s and t need to be incremented and be the same# 2. if s is larger and t is smaller then# s can move one iterator to match the length of t# and t must remain the same length# 3. if t is larger and s is smaller, then# the reverse must be truereturn s[i + s_larger:]== t[i + t_larger:]# if the lengths are the same return Falsereturnabs(len(s) -len(t))==1obj =Solution()print(obj.isOneEditDistance('ab', 'ba'))# Falseprint(obj.isOneEditDistance('abc', 'ab'))# Trueprint(obj.isOneEditDistance('ab', 'cab'))# Trueprint(obj.isOneEditDistance('a', ''))# Trueprint(obj.isOneEditDistance('abb', 'abc'))# Trueprint(obj.isOneEditDistance('a', 'a'))# Falseprint(obj.isOneEditDistance('acc', 'adc'))# Trueprint(obj.isOneEditDistance('kkk', 'kkc'))# Trueprint(obj.isOneEditDistance('lmk', 'kml'))# Falseprint(obj.isOneEditDistance('abcde', 'abfde'))# Trueprint(obj.isOneEditDistance('abcde', 'abffe'))# False