Skip to content

Commit a01e3cd

Browse files
committed
add explanation
1 parent 0ce29ec commit a01e3cd

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Strings/one_edit.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,30 @@
77
Replace: One character in one string is swapped for a different character.
88
Add:: One character is added at any index in one string.
99
Remove: One character is removed at any index in one string.
10+
11+
Explanation:
12+
The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given
13+
strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character.
14+
15+
The `OneEdit` function takes two strings as input and returns a boolean indicating whether
16+
they are one edit away. Here's the breakdown of the algorithm:
17+
18+
1. Calculate the lengths of the two strings.
19+
2. Check if the difference in lengths is greater than 1. If so, return `false` because it's
20+
not possible to make one edit to make the strings equal.
21+
3. Traverse both strings until the shorter one is fully traversed or an unequal character is
22+
found.
23+
4. If an unequal character is found, check the remaining portion of the strings to determine
24+
if they are still one edit away.
25+
5. Check the remaining characters in the longer string compared to the remaining characters
26+
in the shorter string.
27+
6. Return `true` if the remaining portions match, indicating they are one edit away.
28+
7. If the loop completes without finding any unequal characters, the strings are either
29+
identical or differ only in length by 1, which means they are one edit away.
30+
8. The `abs` and `min` functions are utility functions used to calculate the absolute value
31+
and minimum of two integers, respectively.
32+
33+
The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different.
1034
1135
1236
*/

0 commit comments

Comments
 (0)