代码改变世界

[LeetCode] 161. One Edit Distance_Medium

2018-07-20 03:45  Johnson_强生仔仔  阅读(195)  评论(0编辑  收藏  举报

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