Skip to content

Instantly share code, notes, and snippets.

@dolphinsue319
Last active November 21, 2021 06:48
Show Gist options
  • Save dolphinsue319/b9ef7e166b5afec63633966151cdd610 to your computer and use it in GitHub Desktop.
Save dolphinsue319/b9ef7e166b5afec63633966151cdd610 to your computer and use it in GitHub Desktop.
LeetCode 161. One Edit Distance
class Solution {
func isOneEditDistance(_ s: String, _ t: String) -> Bool {
if (s.count == t.count) {
return countOfReplaced(s, t) == 1
}
if (s.count == t.count - 1) {
return isRemoved(s, t)
}
if (t.count == s.count - 1) {
return isRemoved(t, s)
}
return false
}
private func isRemoved(_ shortS: String, _ longS: String) -> Bool {
for i in 0..<longS.count {
let newLongS = remove(index: i, from: longS)
if (newLongS == shortS) {
return true
}
}
return false
}
private func countOfReplaced(_ s: String, _ t: String) -> Int {
var count = 0
for i in 0..<s.count {
if (s[i...i] != t[i...i]) {
count += 1
}
}
return count
}
private func remove(index: Int, from string: String) -> String {
var newString = string
let i = newString.index(newString.startIndex, offsetBy: index)
newString.remove(at: i)
return newString
}
}
extension String {
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment