Program to count number of unique subsequences of a string in C++

C++Server Side ProgrammingProgramming

Suppose we have a string s, we have to find the number of non-empty unique subsequences of s. If the answer is very large then mod the result by 10^9 + 7.

So, if the input is like s = "xxy", then the output will be 5, as there are five subsequences: "x", "xx", "xy", "y" and "xxy".

To solve this, we will follow these steps −

  • m := 10^9 + 7

  • n := size of s

  • Define an array table of size 26

  • res := 0

  • for initialize i := 1, when i <= n, update (increase i by 1), do−

    • c := s[i − 1] − ASCII of 'a'

    • curr := (res + 1 − table[c] + m) mod m

    • res := (res + curr) mod m

    • table[c] := (table[c] + curr) mod m

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int m = 1e9 + 7;
int solve(string s) {
   int n = s.size();
   vector<int> table(26);
   long long res = 0;
   for (int i = 1; i <= n; ++i) {
      int c = s[i − 1] − 'a';
      int curr = (res + 1 − table[c] + m) % m;
      res = (res + curr) % m;
      table[c] = (table[c] + curr) % m;
   }
   return res;
}
int main(){
   string s = "xxy";
   cout << solve(s);
}

Input

"xxy"

Output

5
raja
Published on 26-Dec-2020 15:22:39
Advertisements