|
| 1 | +#include <iostream> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string> |
| 4 | +#include <algorithm> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// Function to calculate the edit aka levenshtein distance |
| 8 | +// src is the source string |
| 9 | +// dst is the destination string |
| 10 | +int leven(string src, string dst) |
| 11 | +{ |
| 12 | + int n = src.length(); |
| 13 | + int m = dst.length(); |
| 14 | + |
| 15 | + // Creating a dynamic programming table for storing value of subproblems |
| 16 | + // table[i][j] = levenshtien distance for the strings src[i...n-1] and dst[j...m-1] |
| 17 | + // i = n and j = m refer to special case of end of string |
| 18 | + |
| 19 | + int table[n+1][m+1]; |
| 20 | + int i, j; |
| 21 | + |
| 22 | + // Base case declaration |
| 23 | + // For every i, table[i][m] (end of dst) = n-i (Hence counting for adding characters to src) |
| 24 | + for(i = 0; i < n+1; i++) table[i][m] = n - i; |
| 25 | + |
| 26 | + // For every j, table[n][j] (end of src) = m-j (Hence contributing for deleting characters from src) |
| 27 | + for(j = 0; j < m+1; j++) table[n][j] = m - j; |
| 28 | + |
| 29 | + // Start from i = n-1 and j = m-1 and continue till (0,0) |
| 30 | + for(i = n - 1; i >= 0; i--) |
| 31 | + { |
| 32 | + for(j = m - 1; j >= 0; j--) |
| 33 | + { |
| 34 | + // If characters are equal, move i and j iterators both by one |
| 35 | + // Or table[i][j] = table[i+1][j+1] (no operation required) |
| 36 | + if(src[i] == dst[j]) table[i][j] = table[i+1][j+1]; |
| 37 | + |
| 38 | + // Else find the min operation result among the following operations: |
| 39 | + // table[i+1][j] (meaning deletion of src[i]) |
| 40 | + // table[i][j+1] (meaning addition to src[i]) |
| 41 | + // table[i+1][j+1] (meaning substitution of src[i]) |
| 42 | + // Add 1 to each (for cost of operation) and take min of them |
| 43 | + else{ |
| 44 | + table[i][j] = min(table[i+1][j] + 1, min(table[i][j+1] + 1, table[i+1][j+1]+1)); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + // Table[0][0] now contains the answer |
| 50 | + return table[0][0]; |
| 51 | + |
| 52 | +} |
| 53 | + |
| 54 | +int main() |
| 55 | +{ |
| 56 | + string src, dst; |
| 57 | + // Input src and dst strings |
| 58 | + cin >> src >> dst; |
| 59 | + |
| 60 | + // Output the result |
| 61 | + cout << leven(src, dst) << endl; |
| 62 | + return 0; |
| 63 | +} |
0 commit comments