Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
70 lines (56 loc) · 2.06 KB

File metadata and controls

70 lines (56 loc) · 2.06 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
63
64
65
66
67
68
69
70
"""
One Edit Distance
Given two strings, determine if they are exactly one edit distance apart.
An edit is an insertion, deletion, or replacement of a single character.
Reference: https://leetcode.com/problems/one-edit-distance/
Complexity:
Time: O(n) where n is the length of the shorter string
Space: O(n) for string slicing
"""
from __future__ import annotations
def is_one_edit(source: str, target: str) -> bool:
"""Check if two strings are exactly one edit apart using slicing.
Args:
source: The first string.
target: The second string.
Returns:
True if the strings are exactly one edit apart, False otherwise.
Examples:
>>> is_one_edit("abc", "abd")
True
"""
if len(source) > len(target):
return is_one_edit(target, source)
if len(target) - len(source) > 1 or target == source:
return False
for index in range(len(source)):
if source[index] != target[index]:
return (
source[index + 1 :] == target[index + 1 :]
or source[index:] == target[index + 1 :]
)
return True
def is_one_edit2(source: str, target: str) -> bool:
"""Check if two strings are exactly one edit apart using modification.
Args:
source: The first string.
target: The second string.
Returns:
True if the strings are exactly one edit apart, False otherwise.
Examples:
>>> is_one_edit2("abc", "abd")
True
"""
source_length, target_length = len(source), len(target)
if source_length > target_length:
return is_one_edit2(target, source)
if len(target) - len(source) > 1 or target == source:
return False
for index in range(len(source)):
if source[index] != target[index]:
if source_length == target_length:
source = source[:index] + target[index] + source[index + 1 :]
else:
source = source[:index] + target[index] + source[index:]
break
return source == target or source == target[:-1]
Morty Proxy This is a proxified and sanitized view of the page, visit original site.