Edit once

Edit once

There are three editing operations for strings: insert a character, delete a character, or replace a character. Given two strings, write a function to determine whether they require only one (or zero) editing.

Example 1:

  • enter: 
  • first = "pale"
  • second = "ple"
  • Output: True

Example 2:

  • enter: 
  • first = "pales"
  • second = "pal"
  • Output: False

Sample code:

class Solution(object):
    def oneEditAway(self, first, second):
        """
        :type first: str
        :type second: str
        :rtype: bool
        """
        if abs(len(first) - len(second)) > 1:
            return False
        if len(second) - len(first) < 0:
            first, second = second, first
        for i in range(len(first)):
            if first[i] == second[i]:
                continue
            return first[i:] == second[i+1:] or first[i+1:] == second[i+1:]
        return True


a = Solution()
# b = a.oneEditAway("pale", "pal")
b = a.oneEditAway("pales", "pal")
print(b)

running result:

Idea analysis:

Key points:

  •     The feature of the addition, deletion and modification function is: starting from different positions, the follow-ups are the same

Error-prone point:

  •     When comparing, if the first string is relatively long, the index may overflow;
  •     Because addition and deletion are actually reverse operations, you can directly exchange two strings
  •     Note that when comparing changes, it is i+1 not i
  •     Because the second one is definitely longer than the first one, there is only a comparison between increase and change

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/113861210