summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:46:59 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:46:59 +0100
commitad7fd3dccdcd1baefcb637a599bcfa699550c7f5 (patch)
treee1c526439146b2ec02ec1e8716187f2e82fde651 /01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance
parentbc75b20fc0e80d6037ee14e3dccc2d88823f5f2f (diff)
downloadcoursera-ad7fd3dccdcd1baefcb637a599bcfa699550c7f5.zip
coursera-ad7fd3dccdcd1baefcb637a599bcfa699550c7f5.tar.gz
Algorithms : complete 01-algorithmic_toolbox 04-dynamic_programming
Diffstat (limited to '01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance')
-rw-r--r--01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance/edit_distance.cpp41
1 files changed, 38 insertions, 3 deletions
diff --git a/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance/edit_distance.cpp b/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance/edit_distance.cpp
index fd7d16e..8b124ed 100644
--- a/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance/edit_distance.cpp
+++ b/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance/edit_distance.cpp
@@ -3,9 +3,44 @@
using std::string;
-int edit_distance(const string &str1, const string &str2) {
- //write your code here
- return 0;
+int edit_distance(const string &str1, const string &str2)
+{
+ int s1 = str1.length() + 1;
+ int s2 = str2.length() + 1;
+ int *m = new int[s1 * s2];
+
+ for (int i = 0; i < s1; i++) m[i] = i;
+ for (int i = 0; i < s2; i++) m[i * s1] = i;
+
+ for (int i = 1; i < s2; i++) {
+ for (int j = 1; j < s1; j++) {
+ int insertion = m[i * s1 + j - 1] + 1;
+ int deletion = m[(i - 1 ) * s1 + j] + 1;
+ int match = m[(i - 1) * s1 + j - 1];
+ int mismatch = match + 1;
+ if (str2[i - 1] == str1[j - 1]) {
+ /* m[i, j] = ((insertion < deletion) ? */
+ m[i * s1 + j] = ((insertion < deletion) ?
+ ((insertion < match) ? insertion : match)
+ : ((deletion < match) ? deletion : match));
+ }
+ else {
+ m[i * s1 + j] = ((insertion < deletion) ?
+ ((insertion < mismatch) ? insertion : mismatch)
+ : ((deletion < mismatch) ? deletion : mismatch));
+ }
+ }
+ }
+
+ /* for (int i = 0; i < s2; i++) { */
+ /* for (int j = 0; j < s1; j++) */
+ /* std::cout << m[i * s1 + j] << " "; */
+ /* std::cout << std::endl; */
+ /* } */
+
+ delete [] m;
+
+ return m[s1 * s2 - 1];
}
int main() {