File tree Expand file tree Collapse file tree 1 file changed +15
-15
lines changed Expand file tree Collapse file tree 1 file changed +15
-15
lines changed Original file line number Diff line number Diff line change 7
7
class OneEditDistance {
8
8
func isOneEditDistance( _ s: String , _ t: String ) -> Bool {
9
9
let sChars = Array ( s. characters) , tChars = Array ( t. characters)
10
- let sLen = sChars. count, tLen = tChars. count
11
-
12
- guard abs ( sLen - tLen) <= 1 && s != t else {
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
14
+
15
+ guard longer. count - shorter. count < 2 && s != t else {
13
16
return false
14
17
}
15
18
16
- let s1 = sLen < tLen ? sChars : tChars, s2 = sLen < tLen ? tChars : sChars
17
- var index1 = 0 , index2 = 0 , foundDiff = false
18
-
19
- while index1 < s1. count && index2 < s2. count {
20
- if s1 [ index1] != s2 [ index2] {
19
+ while i < shorter. count && j < longer. count {
20
+ if shorter [ i] != longer [ j] {
21
21
if foundDiff {
22
22
return false
23
23
}
24
- foundDiff = true
25
24
26
- if s1. count < s2. count {
27
- index2 += 1
25
+ foundDiff = true
26
+ if shorter. count < longer. count {
27
+ j += 1
28
28
} else {
29
- index1 += 1
30
- index2 += 1
29
+ i += 1
30
+ j += 1
31
31
}
32
32
} else {
33
- index1 += 1
34
- index2 += 1
33
+ i += 1
34
+ j += 1
35
35
}
36
36
}
37
37
You can’t perform that action at this time.
0 commit comments