-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.java
74 lines (56 loc) · 1.83 KB
/
15.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//{ Driver Code Starts
// Initial Template for Java
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
String str1 = sc.next();
String str2 = sc.next();
Solution obj = new Solution();
String ans = obj.betterString(str1, str2);
System.out.println(ans);
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
// Function to calculate the number of distinct subsequences
static int countDistinctSubsequences(String str) {
int MOD = 1000000007;
int n = str.length();
int[] lastOccurrence = new int[256];
Arrays.fill(lastOccurrence, -1);
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = (2 * dp[i - 1]) % MOD;
if (lastOccurrence[str.charAt(i - 1)] != -1) {
dp[i] = (dp[i] - dp[lastOccurrence[str.charAt(i - 1)] - 1] + MOD) % MOD;
}
lastOccurrence[str.charAt(i - 1)] = i;
}
return dp[n] - 1; // Subtract 1 to exclude the empty subsequence
}
// Function to find the better string
static String betterString(String str1, String str2) {
int count1 = countDistinctSubsequences(str1);
int count2 = countDistinctSubsequences(str2);
if (count1 >= count2) {
return str1;
} else {
return str2;
}
}
public static void main(String[] args) {
String str1 = "gfg";
String str2 = "ggg";
String result = betterString(str1, str2);
System.out.println("Output: " + result);
}
}