Advertisement
RaFiN_

Count how many distinct subsequences of a string

Jun 26th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. /* Count how many distinct subsequences of a string */
  2.  
  3.  
  4. // C++ program to count number of distinct
  5. // subsequences of a given string.
  6. #include <bits/stdc++.h>
  7. using namespace std;
  8. const int MAX_CHAR = 256;
  9.  
  10. // Returns count of distinct sunsequences of str.
  11. int countSub(string str)
  12. {
  13.     // Create an array to store index
  14.     // of last
  15.     vector<int> last(MAX_CHAR, -1);
  16.  
  17.     // Length of input string
  18.     int n = str.length();
  19.  
  20.     // dp[i] is going to store count of distinct
  21.     // subsequences of length i.
  22.     int dp[n+1];
  23.  
  24.     // Empty substring has only one subsequence
  25.     dp[0] = 1;
  26.  
  27.     // Traverse through all lengths from 1 to n.
  28.     for (int i=1; i<=n; i++)
  29.     {
  30.         // Number of subsequences with substring
  31.         // str[0..i-1]
  32.         dp[i] = 2*dp[i-1];
  33.  
  34.         // If current character has appeared
  35.         // before, then remove all subsequences
  36.         // ending with previous occurrence.
  37.         if (last[str[i-1]] != -1)
  38.             dp[i] = dp[i] - dp[last[str[i-1]]];
  39.  
  40.         // Mark occurrence of current character
  41.         last[str[i-1]] = (i-1);
  42.     }
  43.  
  44.     return dp[n];
  45. }
  46.  
  47. // Driver code
  48. int main()
  49. {
  50.    cout << countSub("gfg");
  51.    return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement