Skip to content

Latest commit

 

History

History
76 lines (60 loc) · 1.62 KB

161. One Edit Distance.md

File metadata and controls

76 lines (60 loc) · 1.62 KB

Given two strings s and t, determine if they are both one edit distance apart.

Note:

There are 3 possiblities to satisify one edit distance apart:

  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. Replace a character of s to get t

Example 1:

Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.

Example 2:

Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.

Example 3:

Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.

Solution

根据字符串的长度,分三种情况比较。

Code

s = "1203"
        t = "1203a"
        len1 = len(s)
        len2 = len(t)
        if len1 == len2:
            count = 0
            for i in range(len1):
                if s[i]!=t[i]:
                    if count == 0:
                        count += 1
                    else:
                        return False
            return count == 1 
        else:
            if len1 == len2+1:
                longer = s
                shorter = t
            elif len2 == len1 + 1:
                longer = t
                shorter = s
            else:
                return False
            
            count = 0
            for i in range(len(shorter)):
                if shorter[i]!=longer[i+count]:
                    if count == 0:
                        count += 1
                    else:
                        return False
            return True