-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path161 One Edit Distance.py
62 lines (51 loc) · 1.41 KB
/
161 One Edit Distance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Premium question
Non-dp version of edit distance
Author: Rajeev Ranjan
"""
class Solution(object):
def isOneEditDistance(self, s, t):
"""
String
:type s: str
:type t: str
:rtype: bool
"""
m, n = len(s), len(t)
if m > n: return self.isOneEditDistance(t, s)
if n-m > 1: return False
diff = 0
i, j = 0, 0
while i < m and j < n and diff < 2:
if s[i] == t[j]:
i += 1
j += 1
else:
if m != n:
j += 1 # delete
else: # replace s[i]
i += 1
j += 1
diff += 1
return diff == 1 or diff == 0 and m != n
class Solution1(object):
def isOneEditDistance(self, s, t):
"""
Iterator version
"""
m, n = len(s), len(t)
if m > n: return self.isOneEditDistance(t, s)
if n-m > 1: return False
diff = 0
i, j = iter(s), iter(t)
a, b = next(i, None), next(j, None)
while a and b and diff < 2:
if a == b:
a, b = next(i, None), next(j, None)
else:
if m != n:
b = next(j, None)
else:
a, b = next(i, None), next(j, None)
diff += 1
return diff == 1 or diff == 0 and m != n