-
Notifications
You must be signed in to change notification settings - Fork 889
/
OneEditDistance.swift
60 lines (50 loc) · 1.46 KB
/
OneEditDistance.swift
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
/**
* Question Link: https://leetcode.com/problems/one-edit-distance/
* Primary idea: Two pointers to determine two strings' mutation
* Time Complexity: O(n), Space Complexity: O(n)
*/
enum Edit {
case insert
case delete
case replace
}
class OneEditDistance {
func isOneEditDistance(_ s: String, _ t: String) -> Bool {
guard s != t else {
return false
}
var editType = Edit.insert
if s.count == t.count {
editType = .replace
} else if s.count - t.count == 1 {
editType = .delete
} else if t.count - s.count == 1 {
editType = .insert
} else {
return false
}
let arr = Array(s), brr = Array(t)
var flag = false, aIdx = 0, bIdx = 0
while aIdx < arr.count && bIdx < brr.count {
if arr[aIdx] != brr[bIdx] {
guard !flag else {
return false
}
flag = true
switch editType {
case .insert:
bIdx += 1
case .delete:
aIdx += 1
case .replace:
aIdx += 1
bIdx += 1
}
} else {
aIdx += 1
bIdx += 1
}
}
return true
}
}