Q32 Number of distinct subsequences | Practice | GeeksforGeeks
Sun Mar 26 2023 10:37:44 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
//{ Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
String s = read.readLine();
Solution ob = new Solution();
System.out.println(ob.distinctSubsequences(s));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution {
int distinctSubsequences(String s) {
//not getting submitted on GFG cause not included mod operations
//every cell denotes no. of distinct subsequences(NODS) till that string
int n = s.length();
//n+1 , as 0th place would be taken by empty subsequence
int dp[] = new int[n+1];
dp[0] = 1 ;//for 1 character string , NODS = 1
//make HM to store latest indexes of repeated characters
HashMap<Character ,Integer> map = new HashMap<>();
for(int i = 1 ; i < n+1 ; i++){
dp[i] = 2*dp[i-1];
char ch = s.charAt(i-1); //dp is 1 greater than string
/* if character already exists means its repeated, so we will subtract all
subsequences of dp[ch - 1] where ch represent last occurence of repeated
character before now, as those are the ones which will get combined and repeated
*/
if(map.containsKey(ch)) {
int idx = map.get(ch); //getting previous occurence of repeated character
dp[i] -= dp[idx- 1];
}
map.put(ch , i); //updating characters
}
return dp[n];
}
}
content_copyCOPY
https://practice.geeksforgeeks.org/problems/number-of-distinct-subsequences0909/1
Comments