【LeetCode】161. One Edit Distance

本文探讨了LeetCode161题目的多种解法,重点对比了一种推荐解法与个人解法,分析了分段思想在字符串问题中的应用。通过Python实现,比较了两种解法的时间和空间效率。

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

LeetCode161 传送门

解法:

    推荐解法和我的解法看似类似,时间、空间复杂度非常接近,但实则简洁很多。究其原因,推荐方法中采用了分段的思想。这种分段的思想很适合于字符串问题。

Python源码:

Runtime: 24 ms, faster than 28.87% of Python online submissions for One Edit Distance.

Memory Usage: 11.8 MB, less than 88.24% of Python online submissions for One Edit Distance.

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        m = len(s)
        n = len(t)
        if m > n:
            return self.isOneEditDistance(t, s)
        if n - m > 1:
            return False
        i = 0
        shift = n-m
        while(i < m and s[i] == t[i]):
            i += 1
        if shift == 0:
            i += 1
        while(i < m and s[i] == t[i + shift]):
            i += 1
        return i == m

我的心路:

    有空字符串的情况判断后。分两种情况,一种是两个字符串等长,一种是一长一短。首先保留一个布尔值edited=False,第一次发现不同时置为True,第二次发现不同时直接返回False;如果长度不等,edit为False时需要考虑最终长的字符串长度与遍历符j大小相差1的情况。

Runtime: 24 ms, faster than 28.74% of Python online submissions for One Edit Distance.

Memory Usage: 11.9 MB, less than 52.94% of Python online submissions for One Edit Distance.

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)+len(t) == 0:
            return False
        elif len(s)+len(t) == 1:
            return True
        
        edited = False
        i = 0
        j = 0
        
        if len(s) < len(t):
            longer = t
            shorter = s
        else:
            longer = s
            shorter = t
            
        if len(s) == len(t):
            while i <= len(s) - 1:
                if s[i] != t[j]:
                    if edited:
                        return False
                    edited = True
                i += 1
                j += 1
        else:
            while i <= len(shorter) - 1:
                if shorter[i] != longer[j]:
                    if edited:
                        return False
                    else:
                        i -= 1
                        edited = True
                i += 1
                j += 1
        
        if (edited and len(longer) - j == 0) or (edited == False and len(s) != len(t) and len(longer) - j == 1):
            return True
        else:
            return False

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值