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