forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy path161_One_Edit_Distance.py
More file actions
34 lines (29 loc) · 1.07 KB
/
161_One_Edit_Distance.py
File metadata and controls
34 lines (29 loc) · 1.07 KB
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
# Generalized anser. Memory limit exceded
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
edits = [[x for x in range(len(s) + 1)] for y in range(len(t) + 1)]
for i in range(1, len(t) + 1):
edits[i][0] = edits[i - 1][0] + 1
for i in range(1, len(t) + 1):
for j in range(1, len(s) + 1):
if t[i - 1] == s[j - 1]:
edits[i][j] = edits[i - 1][j - 1]
else:
edits[i][j] = 1 + min(edits[i][j - 1], edits[i - 1][j - 1], edits[i - 1][j])
return True if edits[-1][-1] == 1 else False
# Accepeted answer
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) > len(t):
return self.isOneEditDistance(t, s)
if len(t) - len(s) > 1 or s == t:
return False
for i in range(len(s)):
if s[i] != t[i]:
return s[i + 1:] == t[i + 1:] or s[i:] == t[i + 1:]
return True