Skip to content

Commit d74c1aa

Browse files
author
Luisa Herrmann
committed
Add minimum edit distance for strings
1 parent 72cac4d commit d74c1aa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
extension String {
2+
3+
public func minimumEditDistance(other: String) -> Int {
4+
let m = self.characters.count
5+
let n = other.characters.count
6+
var matrix = [[Int]](count: m+1, repeatedValue: [Int](count: n+1, repeatedValue: 0))
7+
8+
for index in 1...m {
9+
matrix[index][0]=index
10+
}
11+
for index in 1...n {
12+
matrix[0][index]=index
13+
}
14+
15+
for (i, selfChar) in self.characters.enumerate() {
16+
for (j, otherChar) in other.characters.enumerate() {
17+
if otherChar == selfChar {
18+
matrix[i+1][j+1] = matrix[i][j]
19+
} else {
20+
matrix[i+1][j+1] = min(matrix[i][j]+1, matrix[i+1][j]+1, matrix[i][j+1]+1)
21+
}
22+
23+
}
24+
}
25+
return matrix[m][n]
26+
}
27+
}

0 commit comments

Comments
 (0)