Skip to content

Commit 68392bc

Browse files
author
Yi Gu
committed
[String] optimize code style for One Edit Distance
1 parent ac04173 commit 68392bc

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

String/OneEditDistance.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,31 @@
77
class OneEditDistance {
88
func isOneEditDistance(_ s: String, _ t: String) -> Bool {
99
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 {
1316
return false
1417
}
1518

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] {
2121
if foundDiff {
2222
return false
2323
}
24-
foundDiff = true
2524

26-
if s1.count < s2.count {
27-
index2 += 1
25+
foundDiff = true
26+
if shorter.count < longer.count {
27+
j += 1
2828
} else {
29-
index1 += 1
30-
index2 += 1
29+
i += 1
30+
j += 1
3131
}
3232
} else {
33-
index1 += 1
34-
index2 += 1
33+
i += 1
34+
j += 1
3535
}
3636
}
3737

0 commit comments

Comments
 (0)