File tree 1 file changed +42
-22
lines changed
1 file changed +42
-22
lines changed Original file line number Diff line number Diff line change 4
4
* Time Complexity: O(n), Space Complexity: O(n)
5
5
*/
6
6
7
+ enum Edit {
8
+ case insert
9
+ case delete
10
+ case replace
11
+ }
12
+
7
13
class OneEditDistance {
8
14
func isOneEditDistance( _ s: String , _ t: String ) -> Bool {
9
- let sChars = Array ( s. characters) , tChars = Array ( t. characters)
10
- var foundDiff = false , i = 0 , j = 0
11
-
12
- let shorter = sChars. count < tChars. count ? sChars : tChars
13
- let longer = sChars. count < tChars. count ? tChars : sChars
15
+ guard s != t else {
16
+ return false
17
+ }
18
+ var editType = Edit . insert
14
19
15
- guard longer. count - shorter. count < 2 && s != t else {
16
- return false
20
+ if s. count == t. count {
21
+ editType = . replace
22
+ } else if s. count - t. count == 1 {
23
+ editType = . delete
24
+ } else if t. count - s. count == 1 {
25
+ editType = . insert
26
+ } else {
27
+ return false
17
28
}
18
29
19
- while i < shorter. count && j < longer. count {
20
- if shorter [ i] != longer [ j] {
21
- if foundDiff {
22
- return false
30
+ let arr = Array ( s) , brr = Array ( t)
31
+ var flag = false , aIdx = 0 , bIdx = 0
32
+
33
+ while aIdx < arr. count && bIdx < brr. count {
34
+
35
+ if arr [ aIdx] != brr [ bIdx] {
36
+
37
+ guard !flag else {
38
+ return false
23
39
}
24
40
25
- foundDiff = true
26
- if shorter. count < longer. count {
27
- j += 1
28
- } else {
29
- i += 1
30
- j += 1
41
+ flag = true
42
+
43
+ switch editType {
44
+ case . insert:
45
+ bIdx += 1
46
+ case . delete:
47
+ aIdx += 1
48
+ case . replace:
49
+ aIdx += 1
50
+ bIdx += 1
31
51
}
32
52
} else {
33
- i += 1
34
- j += 1
53
+ aIdx += 1
54
+ bIdx += 1
35
55
}
56
+
36
57
}
37
-
38
- return true
58
+ return true
39
59
}
40
- }
60
+ }
You can’t perform that action at this time.
0 commit comments