Last active
August 29, 2015 14:22
-
-
Save oisdk/d96fc414e820010447ff to your computer and use it in GitHub Desktop.
This file contains 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
func levDis(w1: String, w2: String) -> Int { | |
let (t, s) = (w1.characters, w2.characters) | |
let empty = Repeat(count: s.count, repeatedValue: 0) | |
var mat = [[Int](0...s.count)] + (1...t.count).map{[$0.0] + empty} | |
for (i, tLett) in t.enumerate() { | |
for (j, sLett) in s.enumerate() { | |
mat[i + 1][j + 1] = tLett == sLett ? | |
mat[i][j] : min(mat[i][j], mat[i][j + 1], mat[i + 1][j]).successor() | |
} | |
} | |
return mat.last!.last! | |
} | |
func levDis(w1: String, w2: String) -> Int { | |
let (t, s) = (w1.characters, w2.characters) | |
let empty = Repeat(count: s.count, repeatedValue: 0) | |
var last = [Int](0...s.count) | |
for (i, tLett) in t.enumerate() { | |
var cur = [i + 1] + empty | |
for (j, sLett) in s.enumerate() { | |
cur[j + 1] = tLett == sLett ? last[j] : min(last[j], last[j + 1], cur[j]).successor() | |
} | |
last = cur | |
} | |
return last.last! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment