Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 8, 2021 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/383ffd18dea1e2db003a3bf74a3f0213 to your computer and use it in GitHub Desktop.
Save vrat28/383ffd18dea1e2db003a3bf74a3f0213 to your computer and use it in GitHub Desktop.
Minimum Distance
class Solution {
func minDistance(_ word1: String, _ word2: String) -> Int {
let longestCommonLength = lcsLength(word1, word2)
return word1.count + word2.count - 2 * longestCommonLength
}
func lcsLength(_ s1: String,_ s2:String) -> Int {
var matrix = [[Int]](repeating: [Int](repeating: 0, count: s2.count+1), count: s1.count+1)
for (i, char1) in s1.enumerated() {
for (j, char2) in s2.enumerated() {
if char1 == char2 {
// Common char found, add 1 to highest lcs found so far.
matrix[i+1][j+1] = matrix[i][j] + 1
} else {
// Not a match, propagates highest lcs length found so far.
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
}
}
}
return matrix[s1.count][s2.count]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment