161. One Edit Distance

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

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.
class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        def judge(s1, s2):
            length = len(s2)
            isChange = False
            i, j = 0, 0
            while j < length:
                if s1[i] == s2[j]:
                    i += 1
                    j += 1
                elif not isChange:
                    i += 1
                    isChange = True
                else:
                    return False
            return True
        
        isChange = False
        len_s = len(s)
        len_t = len(t)
        
        if len_s - len_t > 1 or len_t - len_s > 1:
            return False
        if len_s == len_t:
            for i in range(len_s):
                if s[i] != t[i] and not isChange:
                    isChange = True
                elif s[i] != t[i]:
                    return False
            return isChange
        elif len_s > len_t and len_t > 0:
            return judge(s, t)
        elif len_t > len_s and len_s > 0:
            return judge(t, s)
        return True
            

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值