summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/04-dynamic_programming/03-edit_distance
diff options
context:
space:
mode:
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() {