File tree 2 files changed +35
-0
lines changed
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 749
749
937|[ Reorder Data in Log Files] ( ./solutions/0937-reorder-data-in-log-files.js ) |Medium|
750
750
938|[ Range Sum of BST] ( ./solutions/0938-range-sum-of-bst.js ) |Easy|
751
751
939|[ Minimum Area Rectangle] ( ./solutions/0939-minimum-area-rectangle.js ) |Medium|
752
+ 940|[ Distinct Subsequences II] ( ./solutions/0940-distinct-subsequences-ii.js ) |Hard|
752
753
966|[ Vowel Spellchecker] ( ./solutions/0966-vowel-spellchecker.js ) |Medium|
753
754
970|[ Powerful Integers] ( ./solutions/0970-powerful-integers.js ) |Easy|
754
755
976|[ Largest Perimeter Triangle] ( ./solutions/0976-largest-perimeter-triangle.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 940. Distinct Subsequences II
3
+ * https://leetcode.com/problems/distinct-subsequences-ii/
4
+ * Difficulty: Hard
5
+ *
6
+ * Given a string s, return the number of distinct non-empty subsequences of s. Since the answer
7
+ * may be very large, return it modulo 109 + 7.
8
+ *
9
+ * A subsequence of a string is a new string that is formed from the original string by deleting
10
+ * some (can be none) of the characters without disturbing the relative positions of the remaining
11
+ * characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.
12
+ */
13
+
14
+ /**
15
+ * @param {string } s
16
+ * @return {number }
17
+ */
18
+ var distinctSubseqII = function ( s ) {
19
+ const MOD = 1e9 + 7 ;
20
+ const lastOccurrence = new Array ( 26 ) . fill ( - 1 ) ;
21
+ const dp = new Array ( s . length + 1 ) . fill ( 0 ) ;
22
+ dp [ 0 ] = 1 ;
23
+
24
+ for ( let i = 0 ; i < s . length ; i ++ ) {
25
+ const charIndex = s . charCodeAt ( i ) - 97 ;
26
+ dp [ i + 1 ] = ( dp [ i ] * 2 ) % MOD ;
27
+ if ( lastOccurrence [ charIndex ] !== - 1 ) {
28
+ dp [ i + 1 ] = ( dp [ i + 1 ] - dp [ lastOccurrence [ charIndex ] ] + MOD ) % MOD ;
29
+ }
30
+ lastOccurrence [ charIndex ] = i ;
31
+ }
32
+
33
+ return ( dp [ s . length ] - 1 + MOD ) % MOD ;
34
+ } ;
You can’t perform that action at this time.
0 commit comments