[LeetCode] 161. One Edit Distance_Medium

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.


这个题目思路就是,比较s跟t的长度, 只有abs(s-t) <= 1 才有可能, 然后判断是否只差一个值. 感觉这个题目应该算easy吧.


1. Constraints
1) size >= 0
2) element可以是letter也能是数字

2. Ideas
scan T: O(n) S: O(1)

3. Code
1 class Solution:
2     def oneEdit(self, s,t):
3         m, n = len(s), len(t)
4         if abs(m-n) >1 or s ==t: return False
5         if m > n: s, t, m, n = t, s, n, m
6         for i in range(m):
7             if s[i] != t[i]:
8                 return s[i:] == t[i+1:] or s[i+1: ] == t[i+1:]  # note s[m:] 并不会报错, 但是s[m]会报错!
9         return True

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9339463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值