https://leetcode.com/problems/one-edit-distance/description/

Tag: String

Key Points:

  1. Don’t over think it, just a simple string comparison question

Solution

def isOneEditDistance(self, s: str, t: str) -> bool:
		# if two strings are equal, including both empty, they are not one distance
    if s == t:
        return False

		# s is always the longer string
    if len(s) < len(t): 
        s, t = t, s
		
		# s is more than 2 chars longer than t
    if len(s) > len(t) + 1:
        return False
 
	  # Find the idx of first not matched character from s and t
    idx = 0
    while idx < len(t):
        if s[idx] != t[idx]:
		        # s and t has only one diffent character
		        # or s has only one extra char than t. 
            return s[idx+1:] == t[idx+1:] or s[idx+1:] == t[idx:]
        idx+=1
    
    # Have traversed all chars in t and all matched with s 
    # and s must have one extra char because s == t has been handled before
    return True