Skip to content

Instantly share code, notes, and snippets.

@TheNova22
Created October 31, 2020 06:27
Show Gist options
  • Save TheNova22/e745e28ceb41309af789ed105e4a5ff3 to your computer and use it in GitHub Desktop.
Save TheNova22/e745e28ceb41309af789ed105e4a5ff3 to your computer and use it in GitHub Desktop.
Edit Distance
// vim: syntax=swift
func minDistance(_ word1: String, _ word2: String) -> Int {
guard word1.count > 0 && word2.count > 0 else{
return max(word1.count,word2.count)
}
let w1 = Array(word1), w2 = Array(word2), row = w2.count, col = w1.count
var dp = Array(repeating: Array(repeating: 0, count: col+1), count: row+1)
for i in 1..<dp[0].count{
dp[0][i] = i
}
for i in 1..<dp.count{
dp[i][0] = i
}
for i in 1...row{
for j in 1...col{
if w2[i-1] == w1[j-1]{
dp[i][j] = dp[i-1][j-1]
}else{
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
}
}
}
return dp[row][col]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment