Created
October 31, 2020 06:27
-
-
Save TheNova22/e745e28ceb41309af789ed105e4a5ff3 to your computer and use it in GitHub Desktop.
Edit Distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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