|
| 1 | +import java.io.*; |
| 2 | + |
| 3 | +class DistinctSubsequenceOccurrenceCount { |
| 4 | + static int findSubsequenceCount(String S, String T) |
| 5 | + { |
| 6 | + int m = T.length(); |
| 7 | + int n = S.length(); |
| 8 | + |
| 9 | + // T can't appear as a subsequence in S |
| 10 | + if (m > n) |
| 11 | + return 0; |
| 12 | + |
| 13 | + // mat[i][j] stores the count of |
| 14 | + // occurrences of T(1..i) in S(1..j). |
| 15 | + int mat[][] = new int[m + 1][n + 1]; |
| 16 | + |
| 17 | + // Initializing first column with |
| 18 | + // all 0s. An emptystring can't have |
| 19 | + // another string as suhsequence |
| 20 | + for (int i = 1; i <= m; i++) |
| 21 | + mat[i][0] = 0; |
| 22 | + |
| 23 | + // Initializing first row with all 1s. |
| 24 | + // An empty string is subsequence of all. |
| 25 | + for (int j = 0; j <= n; j++) |
| 26 | + mat[0][j] = 1; |
| 27 | + |
| 28 | + // Fill mat[][] in bottom up manner |
| 29 | + for (int i = 1; i <= m; i++) { |
| 30 | + for (int j = 1; j <= n; j++) { |
| 31 | + // If last characters don't match, |
| 32 | + // then value is same as the value |
| 33 | + // without last character in S. |
| 34 | + if (T.charAt(i - 1) != S.charAt(j - 1)) |
| 35 | + mat[i][j] = mat[i][j - 1]; |
| 36 | + |
| 37 | + // Else value is obtained considering two cases. |
| 38 | + // a) All substrings without last character in S |
| 39 | + // b) All substrings without last characters in |
| 40 | + // both. |
| 41 | + else |
| 42 | + mat[i][j] = mat[i][j - 1] + mat[i - 1][j - 1]; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /* uncomment this to print matrix mat |
| 47 | + for (int i = 1; i <= m; i++, cout << endl) |
| 48 | + for (int j = 1; j <= n; j++) |
| 49 | + System.out.println ( mat[i][j] +" "); */ |
| 50 | + return mat[m][n]; |
| 51 | + } |
| 52 | + |
| 53 | + // Driver code to check above method |
| 54 | + public static void main(String[] args) |
| 55 | + { |
| 56 | + String T = "ge"; |
| 57 | + String S = "geeksforgeeks"; |
| 58 | + System.out.println(findSubsequenceCount(S, T)); |
| 59 | + } |
| 60 | +} |
0 commit comments