1-
2- #include < bits/stdc++.h>
1+ #include < iostream>
2+ #include < vector>
3+ #include < string>
34using namespace std ;
45
5- const int prime = 1e9 + 7 ;
6-
7- // Function to count the number of distinct subsequences of s2 in s1
8- int subsequenceCounting (string &s1, string &s2, int n, int m) {
9- // Create an array to store the count of distinct subsequences for each character in s2
10- vector<int > prev (m + 1 , 0 );
11-
12- // Initialize the count for an empty string (base case)
13- prev[0 ] = 1 ;
14-
15- // Iterate through s1 and s2 to calculate the counts
16- for (int i = 1 ; i <= n; i++) {
17- for (int j = m; j >= 1 ; j--) { // Iterate in reverse direction to avoid overwriting values prematurely
18- if (s1[i - 1 ] == s2[j - 1 ]) {
19- // If the characters match, we have two options:
20- // 1. Match the current characters and add to the previous count (prev[j-1])
21- // 2. Leave the current character in s1 and match s2 with the previous characters (prev[j])
22- prev[j] = (prev[j - 1 ] + prev[j]) % prime;
6+ // Space Optimization version
7+ class Solution {
8+ public:
9+ int editDistance (string start, string target) {
10+ int n = start.size ();
11+ int m = target.size ();
12+ vector<int > prev (m + 1 , 0 ), curr (m + 1 , 0 );
13+ for (int j = 0 ; j <= m; j++) prev[j] = j;
14+ for (int i = 1 ; i <= n; i++) {
15+ curr[0 ] = i;
16+ for (int j = 1 ; j <= m; j++) {
17+ if (start[i - 1 ] == target[j - 1 ])
18+ curr[j] = prev[j - 1 ];
19+ else
20+ curr[j] = 1 + min (prev[j - 1 ], min (curr[j - 1 ], prev[j]));
2321 }
24- // No need for an else statement since we can simply leave the previous count as is
22+ prev = curr;
2523 }
24+ return curr[m];
2625 }
27-
28- // The value at prev[m] contains the count of distinct subsequences
29- return prev[m];
30- }
26+ };
3127
3228int main () {
33- string s1 = " babgbag" ;
34- string s2 = " bag" ;
35-
36- // Call the subsequenceCounting function and print the result
37- cout << " The Count of Distinct Subsequences is " << subsequenceCounting (s1, s2, s1.size (), s2.size ());
29+ string s1, s2;
30+ cout << " Enter first string: " ;
31+ cin >> s1;
32+ cout << " Enter second string: " ;
33+ cin >> s2;
34+ Solution sol;
35+ int result = sol.editDistance (s1, s2);
36+ cout << " Edit Distance: " << result << endl;
3837 return 0 ;
39- }
38+ }
0 commit comments