Skip to content

Commit 5990639

Browse files
authored
[String] Refactor solution to one edit distance
1 parent 1b56f48 commit 5990639

File tree

1 file changed

+42
-22
lines changed

1 file changed

+42
-22
lines changed

String/OneEditDistance.swift

+42-22
Original file line numberDiff line numberDiff line change
@@ -4,37 +4,57 @@
44
* Time Complexity: O(n), Space Complexity: O(n)
55
*/
66

7+
enum Edit {
8+
case insert
9+
case delete
10+
case replace
11+
}
12+
713
class OneEditDistance {
814
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
1419

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
1728
}
1829

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
2339
}
2440

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
3151
}
3252
} else {
33-
i += 1
34-
j += 1
53+
aIdx += 1
54+
bIdx += 1
3555
}
56+
3657
}
37-
38-
return true
58+
return true
3959
}
40-
}
60+
}

0 commit comments

Comments
 (0)