File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } binary
3
+ * @return {number }
4
+ */
5
+ const numberOfUniqueGoodSubsequences = function ( binary ) {
6
+ const n = binary . length ,
7
+ P = 1e9 + 7
8
+ let first1Position = - 1 ,
9
+ first0Position = - 1
10
+ for ( let i = 0 ; i < binary . length ; i ++ ) {
11
+ if ( binary [ i ] === '0' && first0Position == - 1 ) {
12
+ first0Position = i
13
+ }
14
+ if ( binary [ i ] === '1' && first1Position == - 1 ) {
15
+ first1Position = i
16
+ }
17
+ if ( first0Position !== - 1 && first1Position !== - 1 ) break
18
+ }
19
+ if ( first1Position === - 1 ) return 1
20
+ if ( first0Position === - 1 ) return n
21
+
22
+ const next0 = new Array ( n ) . fill ( 0 )
23
+ const next1 = new Array ( n ) . fill ( 0 )
24
+ let nextZero = - 1 ,
25
+ nextOne = - 1
26
+ for ( let i = binary . length - 1 ; i >= 0 ; i -- ) {
27
+ next0 [ i ] = nextZero
28
+ next1 [ i ] = nextOne
29
+ if ( binary [ i ] === '0' ) {
30
+ nextZero = i
31
+ } else {
32
+ nextOne = i
33
+ }
34
+ }
35
+ const dp = new Array ( n ) . fill ( - 1 )
36
+ return ( 1 + fn ( first1Position ) ) % P
37
+
38
+ function fn ( index ) {
39
+ if ( index == n ) return 0
40
+ if ( dp [ index ] !== - 1 ) return dp [ index ]
41
+ let result = 1
42
+ if ( next0 [ index ] >= 0 ) {
43
+ result += fn ( next0 [ index ] )
44
+ result %= P
45
+ }
46
+ if ( next1 [ index ] >= 0 ) {
47
+ result += fn ( next1 [ index ] )
48
+ result %= P
49
+ }
50
+ return ( dp [ index ] = result )
51
+ }
52
+ }
You can’t perform that action at this time.
0 commit comments