-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.swift
39 lines (37 loc) · 1.24 KB
/
Solution.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
class Solution {
func oneEditAway(_ first: String, _ second: String) -> Bool {
let m = first.count, n = second.count
if m < n {
return oneEditAway(second, first)
}
if m - n > 1 {
return false
}
var cnt = 0
var firstIndex = first.startIndex
var secondIndex = second.startIndex
if m == n {
while secondIndex != second.endIndex {
if first[firstIndex] != second[secondIndex] {
cnt += 1
if cnt > 1 {
return false
}
}
firstIndex = first.index(after: firstIndex)
secondIndex = second.index(after: secondIndex)
}
return true
} else {
while firstIndex != first.endIndex {
if secondIndex == second.endIndex || (secondIndex != second.endIndex && first[firstIndex] != second[secondIndex]) {
cnt += 1
} else {
secondIndex = second.index(after: secondIndex)
}
firstIndex = first.index(after: firstIndex)
}
}
return cnt < 2
}
}