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的长度, 只有abs(s-t) <= 1 才有可能, 然后判断是否只差一个值. 感觉这个题目应该算easy吧. 1. Constraints
1) size >= 0
2) element可以是letter也能是数字 2. Ideas
scan T: O(n) S: O(1) 3. Code
class Solution:
def oneEdit(self, s,t):
m, n = len(s), len(t)
if abs(m-n) >1 or s ==t: return False
if m > n: s, t, m, n = t, s, n, m
for i in range(m):
if s[i] != t[i]:
return s[i:] == t[i+1:] or s[i+1: ] == t[i+1:] # note s[m:] 并不会报错, 但是s[m]会报错!
return True