|
1 |
| -package main |
2 |
| - |
3 | 1 | func OneEdit(stringOne string, stringTwo string) bool {
|
4 |
| - lengthOne := len(stringOne) |
5 |
| - lengthTwo := len(stringTwo) |
6 |
| - if abs(lengthOne-lengthTwo) > 1 { |
7 |
| - return false |
8 |
| - } |
9 |
| - for i := 0; i < min(lengthOne, lengthTwo); i++ { |
10 |
| - if stringOne[i] != stringTwo[i] { |
11 |
| - if lengthOne > lengthTwo { |
12 |
| - return stringOne[i+1:] == stringTwo[i:] |
13 |
| - } else if lengthTwo > lengthOne { |
14 |
| - return stringTwo[i+1:] == stringOne[i:] |
15 |
| - } else { |
16 |
| - return stringOne[i+1:] == stringTwo[i+1:] |
17 |
| - } |
18 |
| - } |
19 |
| - } |
20 |
| - return true |
| 2 | + lengthOne := len(stringOne) |
| 3 | + lengthTwo := len(stringTwo) |
| 4 | + |
| 5 | + // Check the difference in lengths between the two strings. |
| 6 | + // If the difference is greater than 1, it is not possible to make one edit to make them equal. |
| 7 | + if abs(lengthOne - lengthTwo) > 1 { |
| 8 | + return false |
| 9 | + } |
| 10 | + |
| 11 | + // Traverse the strings until the shorter one is fully traversed or an unequal character is found. |
| 12 | + for i := 0; i < min(lengthOne, lengthTwo); i++ { |
| 13 | + // If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. |
| 14 | + if stringOne[i] != stringTwo[i] { |
| 15 | + // Check the remaining characters in the longer string compared to the remaining characters in the shorter string. |
| 16 | + // Return true if they match, indicating they are one edit away. |
| 17 | + if lengthOne > lengthTwo { |
| 18 | + return stringOne[i+1:] == stringTwo[i:] |
| 19 | + } else if lengthTwo > lengthOne { |
| 20 | + return stringTwo[i+1:] == stringOne[i:] |
| 21 | + } else { |
| 22 | + return stringOne[i+1:] == stringTwo[i+1:] |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + // If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. |
| 28 | + return true |
21 | 29 | }
|
22 | 30 |
|
23 | 31 | func abs(a int) int {
|
24 |
| - if a < 0 { |
25 |
| - return -a |
26 |
| - } |
27 |
| - return a |
| 32 | + if a < 0 { |
| 33 | + return -a |
| 34 | + } |
| 35 | + return a |
28 | 36 | }
|
| 37 | + |
29 | 38 | func min(a, b int) int {
|
30 |
| - if a < b { |
31 |
| - return a |
32 |
| - } |
33 |
| - return b |
| 39 | + if a < b { |
| 40 | + return a |
| 41 | + } |
| 42 | + return b |
34 | 43 | }
|
0 commit comments