[leetcode] 161. One Edit Distance @ python

本文探讨了判断两个字符串是否可以通过一次插入、删除或替换操作达到一编辑距离的方法。通过分类讨论并提供示例,展示了如何实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

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:

Insert a character into s to get t
Delete a character from s to get t
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.

解法

根据题意, s能转化为t的条件是两个的长度的差不超过1, 因此先排除那些长度的差大于1的情况. 然后分类讨论, 尝试将s变为t.

代码

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        len_s, len_t = len(s), len(t)
        if not(len_s - len_t in [-1, 0, 1]):
            return False
        
        s, t = list(s), list(t)
        if len_s < len_t:
            # try to insert a char to get t
            for i, ch in enumerate(s):
                if s[i] != t[i]:
                    s.insert(i, t[i])
                    # check if they are equal
                    return s == t
            return True
        
        if len_s == len_t:
            for i, ch in enumerate(s):
                if s[i] != t[i]:
                    s[i] = t[i]
                    return s == t
        
        if len_s > len_t:
            # try to delete a char
            for i, ch in enumerate(t):
                if s[i] != t[i]:
                    s.pop(i)
                    return s == t
            return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值