From 6c9f66cb114b299e9fecb7cb540d3affc21cfbc5 Mon Sep 17 00:00:00 2001 From: Sagato Samanta <146449356+SagatoSamanta@users.noreply.github.com> Date: Sun, 29 Oct 2023 22:46:11 +0530 Subject: [PATCH 1/2] Create Sagato_distinct --- Sagato_distinct | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Sagato_distinct diff --git a/Sagato_distinct b/Sagato_distinct new file mode 100644 index 0000000..c24a900 --- /dev/null +++ b/Sagato_distinct @@ -0,0 +1,42 @@ +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) { + HashMap map = new HashMap<>(); + int mod = 1000000007; + int n = S.length(); + int[] dp = new int[n + 1]; + dp[0] = 1; + + for (int i = 1; i <= n; i++) { + dp[i] = (2 * dp[i - 1])%mod; + + char curr = S.charAt(i - 1); + + if (map.containsKey(curr)) + dp[i] = (dp[i] - dp[map.get(curr)-1] + mod) % mod; + + map.put(curr, i); + } + + return dp[n];// code here + } +} From 1d4780234bb1e7a9684bb4497d4aa7bdee11ceb6 Mon Sep 17 00:00:00 2001 From: Sagato Samanta <146449356+SagatoSamanta@users.noreply.github.com> Date: Sun, 29 Oct 2023 22:50:46 +0530 Subject: [PATCH 2/2] Update Sagato_distinct --- Sagato_distinct | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/Sagato_distinct b/Sagato_distinct index c24a900..fd2275d 100644 --- a/Sagato_distinct +++ b/Sagato_distinct @@ -1,23 +1,15 @@ -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(); +class distict +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + String s = sc.nextLine(); Solution ob = new Solution(); System.out.println(ob.distinctSubsequences(s)); } } -} -// } Driver Code Ends - - -//User function Template for Java - + class Solution { int distinctSubsequences(String S) { HashMap map = new HashMap<>(); @@ -26,17 +18,14 @@ class Solution { int[] dp = new int[n + 1]; dp[0] = 1; - for (int i = 1; i <= n; i++) { + for (int i = 1; i <= n; i++) + { dp[i] = (2 * dp[i - 1])%mod; - char curr = S.charAt(i - 1); - if (map.containsKey(curr)) dp[i] = (dp[i] - dp[map.get(curr)-1] + mod) % mod; - map.put(curr, i); } - - return dp[n];// code here + return dp[n]; } }