1
+ /* A Dynamic Programming based C program to find minimum
2
+ number operations to convert string1 to string2 */
3
+ #include <stdio.h>
4
+ #include <string.h>
5
+ // Utility function to find the minimum of three numbers
6
+ int minimum_count (int c1 , int c2 , int c3 )
7
+ {
8
+ if (c1 <=c2 && c1 <=c3 )
9
+ return c1 ;
10
+ if (c2 <=c1 && c2 <=c3 )
11
+ return c2 ;
12
+ else
13
+ return c3 ;
14
+ }
15
+ int edit_DistDP (char str1 [], char str2 [], int Len1 , int Len2 )
16
+ {
17
+ // Create a table to store results of subproblems
18
+ int dp [Len1 + 1 ][Len2 + 1 ];
19
+ // Fill d[][] in bottom up manner
20
+ for (int indexstr1 = 0 ; indexstr1 <= Len1 ; indexstr1 ++ ) {
21
+ for (int indexstr2 = 0 ; indexstr2 <= Len2 ; indexstr2 ++ ) {
22
+ /* If first string is empty, only option is to
23
+ insert all characters of second string */
24
+ if (indexstr1 == 0 )
25
+ // Min. operations = indexstr2
26
+ dp [indexstr1 ][indexstr2 ] = indexstr2 ;
27
+ /* If second string is empty, only option is to
28
+ remove all characters of second string */
29
+ else if (indexstr2 == 0 )
30
+ dp [indexstr1 ][indexstr2 ] = indexstr1 ; // Min. operations = loop
31
+ /* If last characters are same, ignore last char
32
+ and recur for remaining string */
33
+ else if (str1 [indexstr1 - 1 ] == str2 [indexstr2 - 1 ])
34
+ dp [indexstr1 ][indexstr2 ] = dp [indexstr1 - 1 ][indexstr2 - 1 ];
35
+ /* If the last character is different, consider all
36
+ possibilities and find the minimum */
37
+ else
38
+ dp [indexstr1 ][indexstr2 ] = 1 + mincount (dp [indexstr1 ][indexstr2 - 1 ], // Insert
39
+ dp [indexstr1 - 1 ][indexstr2 ], // Remove
40
+ dp [indexstr1 - 1 ][indexstr2 - 1 ]); // Replace
41
+ }
42
+ }
43
+ return dp [Len1 ][Len2 ];
44
+ }
45
+ // Driver program
46
+ int main ()
47
+ {
48
+ char s1 [20 ];
49
+ char s2 [20 ];
50
+ int n ;
51
+ printf ("\n Input: " );
52
+ printf ("\n Enter the first string:" );
53
+ scanf ("%[^\n]%*c" , s1 );
54
+ printf ("\n Enter the second string:" );
55
+ scanf ("%[^\n]%*c" , s2 );
56
+ n = edit_DistDP (s1 , s2 , strlen (s1 ), strlen (s2 ));
57
+ printf ("\n Output:" );
58
+ printf (" %d\n " , n );
59
+ return 0 ;
60
+ }
61
+ /*
62
+ Input:
63
+ Enter the first string: "sunday"
64
+ Enter the second string: "saturday"
65
+ Output: 3
66
+ */
0 commit comments